c++ - 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_
为. 谢谢您的帮助DefinedExecutable
UndefinedExecutable
解决方案
用于target_compile_definitions
指定给定目标的编译定义:
target_compile_definitions(TestLibrary PUBLIC _SHARED_LIBRARY_)
然后链接的任何可执行文件TestLibrary
都将继承_SHARED_LIBRARY_
定义。
推荐阅读
- javascript - Laravel Vue.js 组件注册
- anaconda - 出现错误:安装 Scrapy 教程的致命错误
- graphql - 如何从 Nativescript Core 应用程序使用 GraphQL API?
- angular - 从角度发送数据时,web-api POST body 对象始终为空
- python - 将函数中的变量作为参数发送时遇到问题
- c++11 - 运行相同 io_service 的两个线程
- javascript - 当对象键javascript中的数组字符串匹配时删除对象
- python - IntegrityError 主键无效
- javascript - Mobx-state-tree:如何将 AnonymousModel 重命名为商店名称
- mysql - 用户喜欢关系的表格设计