首页 > 解决方案 > CMake 添加和删除宏定义以编译共享库/可执行文件

问题描述

我有一个 c++ 代码,我需要以两种方式编译,一个共享库和一个可执行文件,为此,我的一些函数在编译为共享库时需要未定义。所以我决定在我的 CMakeLists.txt中使用#ifdef MACRO和定义。MACRO

这是我的情况:

文件function.cpp

#include <iostream>

#ifdef _SHARED_LIBRARY_

void printSharedLibrary(void)
{
    std::cout << "Shared Library" << std::endl;
}

#else

void printExecutable(void)
{
    std::cout << "Executable" << std::endl;
}

#endif

文件main.cpp

#ifdef _SHARED_LIBRARY_
    void printSharedLibrary(void);
#else
    void printExecutable(void);
#endif

int main (void)
{
    #ifdef _SHARED_LIBRARY_
        printSharedLibrary();
    #else
        printExecutable();
    #endif
}

文件CMakeLists.txt

project(ProjectTest)

message("_SHARED_LIBRARY_ ADDED BELOW")
add_definitions(-D_SHARED_LIBRARY_)

add_library(TestLibrary SHARED functions.cpp)
add_executable(DefinedExecutable main.cpp) // Only here to be able to test the library
target_link_libraries(DefinedExecutable TestLibrary)

message("_SHARED_LIBRARY_ REMOVED BELOW")
remove_definitions(-D_SHARED_LIBRARY_)

add_executable(UndefinedExecutable main.cpp functions.cpp)

输出 :

$> ./DefinedExecutable
Executable

$> ./UndefinedExecutable
Executable

预期输出:

$> ./build/DefinedExecutable
Shared Library

$> ./build/UndefinedExecutable
Executable

为了构建它,我使用:rm -rf build/ ; mkdir build ; cd build ; cmake .. ; make ; cd ..

所以我的问题是有没有办法_SHARED_LIBRARY_为. 谢谢您的帮助DefinedExecutableUndefinedExecutable

标签: c++cmake

解决方案


用于target_compile_definitions指定给定目标的编译定义:

target_compile_definitions(TestLibrary PUBLIC _SHARED_LIBRARY_)

然后链接的任何可执行文件TestLibrary都将继承_SHARED_LIBRARY_定义。


推荐阅读