cmake链接共享库 [英] cmake link shared library on Windows
问题描述
共有3个文件[ mc , mh , main.c ]。
There are 3 files [ m.c,m.h,main.c ].
mh
// m.h
int m();
mc
// m.c
#include <stdio.h>
#include "m.h"
int m(){
printf("Hello,m!\n");
return 0;
}
main.c
// main.c
#include "m.h"
int main(){
return m();
}
$ b $ p
虽然我喜欢共享库CMakeLists.txt
While I prefer shared library(m.dll), I've made the CMakeLists.txt
PROJECT("app1")
ADD_LIBRARY(m SHARED m.c)
ADD_EXECUTABLE(myexe main.c)
TARGET_LINK_LIBRARIES(myexe m)
CMake配置完成并生成。打开app1.sln并使用Visual Studio构建,它会崩溃为 LNK1104:无法打开文件Debug \m.lib。它只能在 ADD_LIBRARY()
中使用 STATIC 。
CMake configuration done and generated done. Opening app1.sln and building with Visual Studio , it crashes as LNK1104:Can't open file "Debug\m.lib". It only works as STATIC at ADD_LIBRARY()
.Can explain why it doesn't work on Windows?
如果我有另一个共享库(mylib.dll),我如何调用其main.c和CMakeLists.txt文件中的函数?
If I got another shared library(mylib.dll),how could I invoke its functions in my main.c and CMakeLists.txt file?
推荐答案
在不同平台上的动态库链接之间也存在差异,这也需要一些额外的代码。好消息是,CMake可以帮助你。我发现 Gernot Klingler 非常有用:以下博文:
There are differences between dynamic library linking on different platforms which also needs some additional code. The good news is, that CMake can help you with this. I found the following blog post by Gernot Klingler very useful:
- Creating and using shared libraries with different compilers on different operating systems
简而言之,您需要为 code> mh 。否则构建过程将不会为名为 m.lib
的静态链接生成导入库(另见 CMAKE_IMPORT_LIBRARY_SUFFIX
)。
In short you need some "export prefix" defined for whatever is declared in m.h
. Otherwise the build process will not generate an "import library" for statically linking named m.lib
(see also CMAKE_IMPORT_LIBRARY_SUFFIX
).
您的代码需要修改:
mh
#include "m_exports.h"
int M_EXPORTS m();
mc
#include "m.h"
#include <stdio.h>
int m(){
printf("Hello,m!\n");
return 0;
}
CMakeLists.txt
$ b
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
include(GenerateExportHeader)
PROJECT("app1")
INCLUDE_DIRECTORIES("${CMAKE_CURRENT_BINARY_DIR}")
ADD_LIBRARY(m SHARED m.c m.h m_exports.h)
GENERATE_EXPORT_HEADER(m
BASE_NAME m
EXPORT_MACRO_NAME M_EXPORTS
EXPORT_FILE_NAME m_exports.h
STATIC_DEFINE SHARED_EXPORTS_BUILT_AS_STATIC)
ADD_EXECUTABLE(myexe main.c)
TARGET_LINK_LIBRARIES(myexe m)
其他参考
- GenerateExportHeader 宏
- cake和GenerateExportHeader
- 如何获取CMake创建一个dll及其匹配的lib文件?
- MSDN:演练:创建和使用动态链接库(C ++ )
- GenerateExportHeader macro
- cmake and GenerateExportHeader
- How do I get CMake to create a dll and its matching lib file?
- MSDN: Walkthrough: Creating and Using a Dynamic Link Library (C++)
这篇关于cmake链接共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!