Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different compile flags for same file in different targets

Tags:

I would like to include a .cpp-file in two different targets (becoming two VS projects after running CMake). I would like to set different COMPILE_FLAGS for these projects.

However, when I do

SET_TARGET_PROPERTIES(myfile.cpp PROPERTIES COMPILE_FLAGS "flags1")
ADD_EXECUTABLE(project1 myfile.cpp)
SET_TARGET_PROPERTIES(myfile.cpp PROPERTIES COMPILE_FLAGS "flags2")
ADD_EXECUTABLE(project2 myfile.cpp)

the flags2 applies for both projects, so it seems like the properties are overwritten on line 3 and not considered on line 2. Is this true or am I missing something? Is there a way to solve this?

like image 328
Philipp Avatar asked Jul 12 '11 14:07

Philipp


2 Answers

Apply the set_target_properties command to the projects and not to the source files:

add_executable(project1 myfile.cpp)
set_target_properties(project1 PROPERTIES COMPILE_FLAGS "flags1")
add_executable(project2 myfile.cpp)
set_target_properties(project2 PROPERTIES COMPILE_FLAGS "flags2")

The flags set on the target will apply to all sources within the target.

like image 98
sakra Avatar answered Oct 11 '22 23:10

sakra


If you adhere to a one target per subdirectory philosophy, you could do the following using add_definitions to add your compile flags.


# in ./CMakeLists.txt
add_subdirectory(project1)
add_subdirectory(project2)   

# in ./project1/CMakeLists.txt:
add_definitions("flags1")
add_executable(project1 ../myfile.cpp)

# in ./project2/CMakeLists.txt:
add_definitions("flags2")
add_executable(project2 ../myfile.cpp)

add_definitions applies to all files compiled in this subdirectory and those under it. You can apply flags to specific files using the following:

set_source_files_properties(myfile.cpp PROPERTIES COMPILE_FLAGS "flags")
like image 25
Shaun Lebron Avatar answered Oct 11 '22 22:10

Shaun Lebron