Relster Relster - 6 days ago 6
C++ Question

Are there environment variables for CMake add_library(<lib> OBJECT <src>)?

CMake is 2.8.8 introduced the OBJECT library type when compiling: add_library( OBJECT ). It's a useful construct to be able to compile all classes to .o files, but don't add them to a library yet.

However, I'm not certain what flags it ends up attaching to the command in the generated make files. Basically, when doing a add_library( SHARED ) command, it adds in any flags specified by CMAKE_SHARED_LIBRARY_CXX_FLAGS. I'd like to be able to specify build flags for JUST the OBJECT libraries, without having to resort to the more global flags such as CMAKE_CXX_FLAGS_DEBUG and CMAKE_CXX_FLAGS_RELEASE. Does anyone have any ideas if such a flag exists or is planned?

Recap:

# has CMAKE_SHARED_LIBRARY_CXX_FLAGS to set SHARED library build flags
add_library(<lib> SHARED <srcs>)

# Is any environment variable available to set OBJECT library build flags?
add_library(<lib> OBJECT <srcs>)


I was expecting an environment variable like CMAKE_OBJECT_LIBRARY_CXX_FLAGS to set the OBJECT build flags. Looking through the source (Modules/SystemInformation.in and Modules/CMakeCXXInformation.cmake), I didn't find anything that looked like it was specific to OBJECT libraries.

Edit:
Specifically, I want to add -fPIC to the OBJECT library, but not to the executables, which is why I don't want to specify the flag in CMAKE_CXX_FLAGS_*

Answer

When using CMake 2.8.9 or later, use the property POSITION_INDEPENDENT_CODE to enable position independent code in a compiler independet way:

add_library(<lib> OBJECT <srcs>)
set_target_properties(<lib> PROPERTIES POSITION_INDEPENDENT_CODE ON)

For older versions of CMake, you can set the COMPILE_FLAGS property of the OBJECT_LIBRARY target:

add_library(<lib> OBJECT <srcs>)
set_property(TARGET <lib> PROPERTY COMPILE_FLAGS "-fPIC")