Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

c++ - Pass compound compiler options using cmake

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...