CMake 添加和删除宏定义以编译共享库/可执行文件

CMake Add and Remove a Macro definition to compile Shared Library/Executable

本文关键字:共享 可执行文件 编译 添加 删除 宏定义 CMake      更新时间:2023-10-16

我有一个 c++ 代码,我需要以两种方式编译,共享库和可执行文件,为了做到这一点,我的一些函数在编译为共享库时需要未定义。所以我决定使用#ifdef MACRO并在我的CMakeLists.txt中定义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 ..

所以我的问题是有没有办法为DefinedExecutable的构建定义_SHARED_LIBRARY_,然后为UndefinedExecutable的构建取消定义它。 感谢您的帮助

使用target_compile_definitions为给定目标指定编译定义:

target_compile_definitions(TestLibrary PUBLIC _SHARED_LIBRARY_)

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