CMake 添加和删除宏定义以编译共享库/可执行文件
CMake Add and Remove a Macro definition to compile Shared Library/Executable
我有一个 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_
定义。
相关文章:
- 共享库 (.so) 没有扩展名的 Linux 可执行文件之间的区别?
- Linux 可执行文件通过 dlopen 在emplace_back崩溃打开共享库
- CMake 添加和删除宏定义以编译共享库/可执行文件
- 使用共享库编译可执行文件时仅链接所需的符号
- 不同的数学符号绑定与共享库与 dlopen 并直接链接到可执行文件 (Linux)
- 运行可执行文件时找不到共享库,即使共享库存在于指定的路径中
- 我可以固定C 可执行文件,但不能共享库
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?
- C++ 可执行文件错误:无法打开共享对象文件:没有此类文件或目录
- 除了共享库之外,g++ -fPIC 也适用于可执行文件
- 当使用rpath时,C++可执行文件无法找到动态链接的共享库
- 如何标识其功能当前正由可执行文件执行的共享库
- "make"的输出是一个共享对象,而不是可执行文件
- Cmake不会将共享库的链接依赖关系传播到我的可执行文件
- 作为共享库的 Linux 可执行文件
- 在可执行文件中实现静态方法是否安全,该方法已在共享库中实现
- CMake没有创建可以访问我的共享库的可执行文件
- 为什么 GNU ld 在链接可执行文件和共享对象时以不同的方式解析符号
- 可执行文件、静态库和共享库之间的关系
- 可执行文件中共享库的引用函数,带有重定位,但没有PIC