cmake的链接共享库在Windows [英] cmake link shared library on Windows
问题描述
有3个文件[ M.C 莫氏硬度 的main.c 。
莫氏硬度
// m.h
int m();
M.C
// m.c
#include <stdio.h>
#include "m.h"
int m(){
printf("Hello,m!\n");
return 0;
}
的main.c
main.c
// main.c
#include "m.h"
int main(){
return m();
}
虽然我preFER共享库(m.dll),我做了的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:无法打开文件调试\\ m.lib。它只能作为静态是在 ADD_LIBRARY()
。可以解释为什么它不能在Windows工作?
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?
推荐答案
有不同的平台上还需要一些额外的code链接的动态库之间的差异。好消息是,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
总之你需要一些出口preFIX不管什么在莫氏硬度
声明定义。否则,构建过程将不会产生导入库的静态链接名为 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
).
下面是你的code与修改需要:
Here is your code with the modifications needed:
莫氏硬度
#include "m_exports.h"
int M_EXPORTS m();
M.C
#include "m.h"
#include <stdio.h>
int m(){
printf("Hello,m!\n");
return 0;
}
的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 宏
- cmake并GenerateExportHeader
- How做我得到的CMake来创建一个DLL和它匹配的库文件?
- 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的链接共享库在Windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!