1

I would like your help since I am a newbie when it comes to CMake. Let's say I have an executable target T that depends on source files A.c, B.cpp and c.cpp. I would like to compile A.c with specific flags and create the object file A.o. For simplicity let's assume B and C will be compiled with g++ with the same set of flags, and corresponding object files should be created as B.o C.o. Then I can link these object files and produce the T with gcc. I know I can do it in a few steps with a regular makefile. Basically, I have trouble compiling A.c with specific flags and the rest of the files with same flags. I don't know how exactly it should be done with CMake?

add_executable(T A.c B.cpp C.cpp) 

I know CMake offers a target_compile_options() but I do not how to use it for my case? I guess it can be set for global flags of the target, but not for what I am after!

2
  • 1
    What I ended up doing was to create another library target for A.c, but passed in the OBJECT argument as described in here with desired option and flags. And for the actual target, I was able to use add_executable(T B.cpp C.cpp $<TARGET_OBJECTS:A>). So, B and C will be compiled with the other option, then will be linked with A.o. Commented May 22, 2017 at 0:10
  • Your comment is the correct answer. I suggest writing it as an answer and accepting it as the best. Commented Feb 24, 2024 at 20:54

1 Answer 1

1

If you want to set specific flags for individual source files, you need to work with the source file properties. You use either set_property(SOURCE...) or set_source_files_properties() to do that. The source properties you are likely to be interested in are COMPILE_DEFINITIONS and COMPILE_FLAGS. For example:

# set_source_files_properties() always replaces any previous value set_source_files_properties(A.c PROPERTIES COMPILE_DEFINITIONS MySpecialOption=1 ) # Only set_property() allows appending to existing values set_property(SOURCE A.c APPEND_STRING PROPERTY COMPILE_FLAGS " -Wno-unused" ) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.