简体   繁体   English

使用 CMAKE 将共享库链接到可执行文件

[英]Linking a shared library to an executable using CMAKE

Below is a simple CMake project.下面是一个简单的 CMake 项目。 On Linux, everything compiles, and running main gives expected output.在 Linux 上,一切都编译,运行 main 给出预期的 output。 On Windows, the compilation is successful as well, main doesn't give any output, though.在 Windows 上,编译也是成功的,但是main没有给出任何 output。 I can't really explain the error, but the moment I call getNumber() function from main , main no longer works.我无法真正解释该错误,但是当我从main调用getNumber() function 时, main不再起作用。 I can't even put a breakpoint there and debug it.我什至不能在那里放置断点并对其进行调试。

|-CMakeLists.txt
|-Main
|---main.cpp
|---CmakeLists.txt
|-SHLib
|---foo.h
|---foo.cpp
|---CmakeLists.txt

CMakeLists.txt: CMakeLists.txt:

add_subdirectory(SHLib)
add_subdirectory(Main)

Main/CMakeLists.txt:主要/CMakeLists.txt:

add_executable(Main main.cpp)
target_link_libraries(Main PUBLIC SHLib)

SHLib/CMakeLists.txt SHLib/CMakeLists.txt

add_library(
    SHLib SHARED
    foo.h
    foo.cpp
)

add_compile_definitions(LIBRARY_EXPORTS)
target_include_directories(SHLib PUBLIC "${PROJECT_SOURCE_DIR}")

Main/main.cpp主/main.cpp

#include <iostream>
#include <SHLib/foo.h>

int main()
{
    if (getNumber() == 7)
        std::cout << "Successful linking\n";

    std::cout << "End of main function\n";
}

SHLib/foo.h SHLib/foo.h

#ifdef _WIN32
# ifdef LIBRARY_EXPORTS
#   define LIBRARY_API  __declspec( dllexport )
# else
#   define LIBRARY_API  __declspec( dllimport )
# endif
#else
# define LIBRARY_API
#endif

LIBRARY_API int getNumber();

SHLib/foo.cpp SHLib/foo.cpp

#include <SHLib/foo.h>

int getNumber()
{
    return 7;
}

To make it work on Windows, dll and executable has to be in the same folder.要使其在 Windows、dll 上运行,可执行文件必须位于同一文件夹中。 You can either copy them manually or set output directory in your top CMake file like this: set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "yours_output_directory") .您可以手动复制它们,也可以在顶部 CMake 文件中设置 output 目录,如下所示: set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "yours_output_directory") This way, both executable and dll will end up in yours_output_directory .这样,可执行文件和 dll 都将在yours_output_directory中结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM