0

I am using CMAKE (Android) to build several static and shared libraries. I have one CMakelists.txt file which builds all the shared and static libraries.

Right now I have specified C and C++ compiler flags that apply to all the libraries.

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fpermissive -fno-elide-constructors -DHAVE_POLL -DANDROID -DNO_SSL_DL -DUSE_IPV6 mfloat-abi=softfp -mfpu=neon")

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++14 -fpermissive -fno-elide-constructors -DHAVE_POLL -DANDROID -DNO_SSL_DL -DUSE_IPV6 mfloat-abi=softfp -mfpu=neon")

However, I have a need to specify different sets of C flags and CXX flags for each library that I am building. So for lib1.so I have one set of C and CXX flags and for lib2.so I have another set of C and CXX flags.

I think I can use set_target_properties but I am not sure how and I wasn't able to find an example that shows me how to use set_target_properties to set the C and C++ compiler flags for a library.

user1884325
  • 2,530
  • 1
  • 30
  • 49
  • Per-target compiler options could be set with `target_compile_options` command, as described in [this answer](https://stackoverflow.com/a/28773403/3440745). If you want to define preprocessor macros, then it is better to use `target_compile_definitions`, like in [that answer](https://stackoverflow.com/questions/9017573/define-preprocessor-macro-through-cmake). – Tsyvarev Mar 02 '22 at 17:15
  • Sorry, I don't see any examples in those links that show how to set CMAKE_C_FLAGS and CMAKE_CXX_FLAGS per target library. Could you maybe provide an example? It would be helpful. Thank you. – user1884325 Mar 02 '22 at 18:26
  • Eh? `target_compile_options(first-test PRIVATE -fexceptions)` and `target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)`. What other examples do you want? – Tsyvarev Mar 02 '22 at 18:40
  • Those compiler settings apply to both c and c++ files. I need an example that shows me how to apply C compiler flags to the C files in a target and C++ compiler flags to the C++ files in a target. Some flags cannot be applied to C files, like --std=c++14 – user1884325 Mar 02 '22 at 18:46
  • Have you checked [that question](https://stackoverflow.com/questions/38578801/target-compile-options-for-only-c-files)? It seems exactly about your last problem. – Tsyvarev Mar 02 '22 at 18:56

1 Answers1

1

You need to use target_compile_options/target_compile_definitions with generator expressions.

Something like this:

set(C_FLAGS -some -c -flags)
set(CPP_FLAGS -some -cpp -flags)
set(C_DEFS -DCDEF -DANOTHER_DEF)
set(CPP_DEFS -DCPP_DEF -DANOTHER_DEF)
target_compile_options(YourTarget
  PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${CPP_FLAGS}>" 
          "$<$<COMPILE_LANGUAGE:C>:${C_FLAGS}>"
)
target_compile_definitions(YourTarget
  PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${CPP_DEFS}>"
          "$<$<COMPILE_LANGUAGE:C>:${C_DEFS}>"
)
ixSci
  • 13,100
  • 5
  • 45
  • 79