当前位置:网站首页>Creation and use of static library (win10+vs2022

Creation and use of static library (win10+vs2022

2022-06-27 14:59:00 Alexabc3000

The creation of static library

Use VS2022 New empty project , The project is called MyStaticLib, The folder where the project is located is “E:\temp”.

 

 

Click Create , That is to complete the creation of the project .

stay VS2022 Of “ Solution explorer ” In the view , Add name is “MyStaticLib.h”( The file name can be any ) The header file ( Right click “ The header file - add to - New item - The header file ”),

Enter the following code :

#ifndef _MY_STATIC_LIB_H_
#define _MY_STATIC_LIB_H_

int my_static_add(int a, int b);

#endif

  stay VS2022 Of “ Solution explorer ” In the view , Add name is “MyStaticLib.cpp”( The file name can be any ) Of C++ file ( Right click “ Source file - add to - New item -C++ file ”),

#include "MyStaticLib.h"

int my_static_add(int a, int b)
{
return a+b;
}

  In the project property page , Change the configuration type to “ Static library (.lib)”.

Build solution , The library file can be generated “ E:\temp\MyStaticLib\x64\Debug\MyStaticLib.lib”. 

The use of static libraries

Use VS2022 New empty project , The project is called MyApp, The folder where the project is located is “E:\temp”.

stay VS2022 Of “ Solution explorer ” In the view , For projects MyApp Add name is “main.cpp”( The file name can be any ) Of C++ file ( Right click “ Source file - add to - New item -C++ file ”), Enter the following code :

 

#include <iostream>
//	 The header file containing the static library 
#include "E:\temp\MyStaticLib\MyStaticLib.h"

int main()
{
	int a = 3, b = 5;
	int c = my_static_add(a, b);
	std::cout << "my_static_add(" << a << "," << b << ") = " << c << std::endl;
	return 0;
}

 

At this point, the solution is generated , A link error occurs , The error message is :

main.obj : error LNK2019: Unresolved external symbols "int __cdecl my_static_add(int,int)" ([email protected]@[email protected]), function main The symbol is quoted in

This is an error caused by the connector not finding the library file , The solution is :MyApp Project property page , The linker , Input , Additional dependency , Add dependency “E:\temp\MyStaticLib\x64\Debug\MyStaticLib.lib”

Build solution , The executable file can be generated “E:\temp\MyApp\x64\Debug\MyApp.exe”.

On the command line, enter the directory “E:\temp\MyApp\x64\Debug\”, function MyApp.exe, The operation results are as follows :

 

 

原网站

版权声明
本文为[Alexabc3000]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202161613193427.html