Generator expression "COMPILE_LANG_AND_ID" togheter with CONFIG, how to?

Hi, I am trying to automate different compiler flags based on compiler and config using generator expressions. But it does not work in the way i thought.

target_compile_options(${PROJECT_NAME} PRIVATE
            $<$<COMPILE_LANG_AND_ID:CXX,GNU>:-march=native -mtune=native>
            $<$<COMPILE_LANG_AND_ID:CXX,GNU>:$<CONFIG:Release>:-O3 -DNDEBUG>
            $<$<COMPILE_LANG_AND_ID:CXX,CLANG>:$<CONFIG:Release>:-O3 -DNDEBUG -fsanitize-minimal-runtime>
    )

Using GNU compiler this results in:

-march=native -mtune=native 1:-O3 -DNDEBUG

There is an unexpected additional “1:” and build fails. Can i do this somehow?

CMake sees the space in the middle of your generator expressions as argument separators. You’d have to quote the whole generator expression to preserver spaces. But in this case, you shouldn’t be using spaces, as CMake expects separate flags to be semicolon-separated. If you quoted the generator expressions as is, you’d end up with a compiler command line that escaped the spaces, making gcc see a single command-line option like -march=native\ -mtune=native, which won’t work.

Rather than repeat all the details, I’ll refer you to this Quoting In CMake blog post which goes through the things you need to know. The Generator Expressions section deals directly with your problem, but other parts of that post will be relevant to you as well.

Putting aside the spaces issue addressed in my previous reply, let’s look at your more specific request about how to combine the two expressions you were trying to use. Consider this slightly reduced expression from your original example (I dropped one of the flags to avoid the spaces issue):

The two expressions you want can be combined in a couple of ways. You could use an AND expression:

$<$<AND:$<COMPILE_LANG_AND_ID:CXX,GNU>,$<CONFIG:Release>>:-O3>

Or you could us nesting:

$<$<COMPILE_LANG_AND_ID:CXX,GNU>:$<$<CONFIG:Release>:-O3>>

I think you were aiming for the nested approach, but the AND method might be clearer and less error-prone.

1 Like

Yes the blog is good, and agreed using “AND” shows better intent.

Btw generator expressions is a awesome game-changer!

Thank you