【发布时间】:2019-11-29 09:06:50
【问题描述】:
我有一个 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 的构建取消定义它。
感谢您的帮助
【问题讨论】: