Windows 上的 CMake 链接共享库 [英] CMake link shared library on Windows

查看:34
本文介绍了Windows 上的 CMake 链接共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

共有三个文件,(m.cm.h 和 **main.c*).

There are three files, (m.c,m.h, and **main.c*).

// m.h
int m();

文件 m.c

// m.c
#include <stdio.h>
#include "m.h"

int m(){
    printf("Hello,m!
");
    return 0;
}

文件 main.c

// main.c
#include "m.h"
int main(){
    return m();
}

虽然我更喜欢共享库 (m.dll),但我已经制作了 CMakeLists.txt 文件:

While I prefer a shared library (m.dll), I've made the CMakeLists.txt file:

    PROJECT("app1")
    ADD_LIBRARY(m SHARED m.c)
    ADD_EXECUTABLE(myexe main.c)
    TARGET_LINK_LIBRARIES(myexe m)

CMake 配置完成,生成完成.打开 app1.sln 并使用 Visual Studio 构建,它崩溃为

The CMake configuration is done and generated done. Opening app1.sln and building with Visual Studio, it crashes as

LNK1104:Can't open file "Debugm.lib"

它仅在 ADD_LIBRARY() 中用作 STATIC.为什么它在 Windows 上不起作用?

It only works as STATIC at ADD_LIBRARY(). Why doesn't it 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 files?

推荐答案

不同平台的动态库链接存在差异,也需要一些额外的代码.好消息是,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:

简而言之,您需要为 m.h 中声明的任何内容定义一些导出前缀".否则,构建过程将不会为静态链接名为 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).

这是您需要修改的代码:

Here is your code with the modifications needed:

m.h

#include "m_exports.h"

int M_EXPORTS m();

m.c

#include "m.h"
#include <stdio.h>

int m(){
    printf("Hello,m!
");
    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)

其他参考资料

这篇关于Windows 上的 CMake 链接共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆