Pass compound compiler options using cmake

2019-07-19 08:05发布

问题:

I am trying to pass "compound" options to the compiler using cmake's add_compile_options.

That is, options involving two (or more) flags that must be passed in a particular order and where none of the flags can be ommitted even if they have already be passed to the compiler.

An example would be all the llvm options that must be passed through clang to llvm, e.g., -mllvm -ABC -mllvm -XYZ -mllvm ....

I would prefer not to use CMake's antipattern set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mllvm -ABC") but use something portable like check_cxx_compiler_flag(flag available) + add_compile_option(flag).

However, add_compile_options(-mllvm -XYZ -mllvm -ABC) fails because the -mllvm option gets cached and is only passed once, such that -mllvm -XYZ -ABC is passed resulting in an error.

Furthermore, using quotes "" doesn't help since then the quotes are also passed (i.e. they are not stripped), which also results in an error.

What's the idiomatic way of passing these options with CMake?

回答1:

What you observe here is not CMake preserving quotes.

CMake has special kind of strings - a list. A list is a string, in which elements are delimited with ";". When you write somefunction(A B C) you actually constructing a string "A;B;C", which is also a list of 3 elements. But when you write somefunction("A B C") you are passing a plain string.

Now, when you write add_compile_options("-mllvm -XYZ;-mllvm -ABC"), CMake does correct thing (in a sense) - it passes compiler two command-line arguments, "-mllvm -XYZ" and "-mllvm -ABC". The problem is that clang gets these arguments as two too. That is, argv[i] in clang's main() points to "-mllvm -XYZ" string and clang treats it as single flag.

The only solution i can see is to use CMAKE_{C,CXX}_FLAGS to set these flags. As @Tsyvarev said, it's perfectly ok to use this variable.