Issue
I have a c++ code i need to compile in two ways, a Shared Library and an Executable, In order to do so some of my functions need to be undefined when compiling as a shared library. So i decide to used #ifdef MACRO
and define MACRO
in my CMakeLists.txt.
Here is my case :
File 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
File main.cpp
:
#ifdef _SHARED_LIBRARY_
void printSharedLibrary(void);
#else
void printExecutable(void);
#endif
int main (void)
{
#ifdef _SHARED_LIBRARY_
printSharedLibrary();
#else
printExecutable();
#endif
}
File 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)
Output :
$> ./DefinedExecutable
Executable
$> ./UndefinedExecutable
Executable
Expected Output :
$> ./build/DefinedExecutable
Shared Library
$> ./build/UndefinedExecutable
Executable
in order to build it i use : rm -rf build/ ; mkdir build ; cd build ; cmake .. ; make ; cd ..
So my question is Is there a way to define _SHARED_LIBRARY_
for the build of DefinedExecutable
and then undefine it for the build of UndefinedExecutable
.
Thanks for the help
Solution
Use target_compile_definitions
to specify compile definitions for the given target:
target_compile_definitions(TestLibrary PUBLIC _SHARED_LIBRARY_)
Then any executable linked against TestLibrary
will inherit _SHARED_LIBRARY_
definition.
Answered By - Evg