链接
链接库项目
链接文件:静态链接库、头文件
静态链接库
VS2022
In All Configurations All Platforms
- VS
Configuration Properties => General => Configuration Type
=.lib
- CMake
add_library([lib] STATIC [src])
动态链接库
- VS
Configuration Properties => General => Configuration Type
=.dll
- CMake
add_library([lib] SHARED [src])
导出
_declspec(dllexport)
1 2 3 4 5 6 7 8 9 10 11
#ifdef EXPORTDLL_EXPORTS #define EXPORTDLL_API `_declspec(dllexport)` #elseEXPORTDLL_API `_declspec(dllimport)` #endif class EXPORTDLL_API CExportDLL { public: CExportDLL(void); } extern EXPORTDLL_API int nExportDLL; EXPORTDLL_API int fnExportDLL(void);
.def
Configuration Properties => Linker => 模块定义文件
=xxx.def
LIBRARY [DLLName] EXPORTS [Func]
代码
- 头文件
- C++文件
- 命名空间
链接到静态链接库
- Include head file
- using path(relative or non)
- VS
Configuration Properties => C/C++ => General => Additional Include Directories
+=$(SoIutionDir)[ProjectFolder]\[HeaderFolder]
- CMake
include_directories([path])
- Link the Static Library
- VS
- Configurate in Linker
- Configuration Properties => Linker
- =>
General => Additional Library Directories
+=$(SoIutionDir)...
- =>
Input =>AddtionaI Dependencies
+=xxx.lib
#pragma comment(lib,"[lib directory]/xxx.lib")
- Project Add Reference(VS Library Project)
- Configurate in Linker
- CMake
target_include_directories([target] [path])
target_link_libraries([target] [lib])
- VS
链接到动态链接库
除连接器设置外与静态链接库一致
引导库xxxdll.lib可避免动态链接时的动态查找
- VS
Configuration Properties => Linker => Input =>AddtionaI Dependencies
+=xxxdll.lib
- CMake
target_link_libraries([target] [lib])
- VS
- Add .dll file to .exe directory
- CMake
add_custom_command(TARGET [target] POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:[lib]> $<TARGET_FILE_DIR:[target]> )
- CMake
其它
1、 _declspec(dllexport)
与_declspec(dllimport)
是相互呼应,只有在DLL内部用dllexport作了声明,才能在外部函数中用dllimport导入相关代码
2、如果vs中的dll项目内部的函数前面都没有 _declspec(dllexport)
,则无法生成导出库lib,只有dll生成
3、lib库原理上应该是不做链接过程的,我在一个lib项目上,故意犯下链接错误,编译并不报错。另外,我的一个lib项目,想把opencv的dll库包进来,成为一个包含了opencv功能的lib库,是不行的,因为在这个lib项目中,在vs编译器中都找不到linker选项,再次说明lib库不做链接
4、回到cherno的问题,因为这个项目已经用了引导库lib,所以不需要_declspec(dllimport),就已经能够使用dll库了。lib就是起到定位dll的作用,所以用不用这个_declspec(dllimport)都无所谓。*但如果此项目不用lib引导库,那必须使用_declspec(dllimport)来定位dll中的导出函数。