Alain Zeyu Lou
Alain Zeyu Lou

Reputation: 59

Cmake (< 3.6) compiler flags in custom command

Suppose I have a set of compiler flags and I have two targets

set(COMPILE_FLAGS "-a -b -c")

add_executable(exe main.cpp)
set_target_properties(exe PROPERTIES COMPILE_FLAGS ${COMPILE_FLAGS})
add_custom_target(target1 DEPENDS exe)

add_custom_target(target2 DEPENDS exe2)
separate_arguments(COMPILE_FLAGS)
add_custom_command(OUTPUT ${DEVICE_OBJ_FILE} 
                    COMMAND ${CMAKE_CXX_COMPILER} ${COMPILE_FLAGS} ${OTHER_FLAGS} main.cpp -o exe2
                    DEPENDS source.cpp)

is there anyway to avoid having to call "separate_arguments"

I would rather set FLAGS as semicolon seperated list and COMPILE_OPTIONS instead of COMPILE_FLAGS, but the latest cmake we have access to is 3.6

Upvotes: 0

Views: 495

Answers (1)

mydisplayname
mydisplayname

Reputation: 356

target_compile_options() goes back to at least CMake 3.0 and should probably be the preferred way to set these kind of flags. It takes a list.

CMakeLists.txt (Note: I used -D??? as the flags. Normally one should use target_compile_definitions() for defines.)

cmake_minimum_required(VERSION 3.6)

project ("example" CXX)

set(COMPILE_FLAGS -DAYE -DBEE -DSEE)
set(OTHER_FLAGS -DDEE -DEEE)

add_executable(exe main.cpp)
target_compile_options(exe PRIVATE ${COMPILE_FLAGS})
add_custom_command(OUTPUT exe2
                   COMMAND ${CMAKE_CXX_COMPILER} ${COMPILE_FLAGS} ${OTHER_FLAGS} ${CMAKE_CURRENT_LIST_DIR}/main.cpp -o exe2
                   DEPENDS main.cpp)
add_custom_target(target2 DEPENDS exe2)

main.cpp (exe outputs The sum is 3 while exe2 outputs The sum is 5

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    int sum = 0;
#ifdef AYE 
    sum++;
#endif
#ifdef BEE 
    sum++;
#endif
#ifdef SEE 
    sum++;
#endif
#ifdef DEE 
    sum++;
#endif
#ifdef EEE 
    sum++;
#endif
    printf("The sum is %d\n", sum);
}

Upvotes: 1

Related Questions