[CMake] Howto compile static executable?

Marcel Loose loose at astron.nl
Wed Sep 29 04:46:25 EDT 2010


On Tue, 2010-09-28 at 18:57 +0200, Eric Noulard wrote:
> Hi All,
> 
> I have project which (cross-)compile some simple C applications
> with some bare CMake statement like this:
> 
> add_executable(myapp myapp.c)
> 
> no target_link_libraries, no dep,  etc...
> 
> I want to build fully static executable (even for libc etc...)
> Currently I do:
> 
> set_target_properties(myapp PROPERTIES LINK_FLAGS_DEBUG "-static")
> 
> is there a better and portable way to require "static" executable?
> 
> I am aware of the BUILD_SHARED_LIBS var for globally controlling
> static vs dynamic libs but how can I do for executable?
> 
Hi Eric,

I use an option for this. See the code snippet below.

  if(BUILD_STATIC_EXECUTABLES)
    set(CMAKE_EXE_LINKER_FLAGS -static)
    set(CMAKE_FIND_LIBRARY_SUFFIXES .a)
    set(CMAKE_EXE_LINK_DYNAMIC_C_FLAGS)       # remove -Wl,-Bdynamic
    set(CMAKE_EXE_LINK_DYNAMIC_CXX_FLAGS)
    set(CMAKE_SHARED_LIBRARY_C_FLAGS)         # remove -fPIC
    set(CMAKE_SHARED_LIBRARY_CXX_FLAGS)
    set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS)    # remove -rdynamic
    set(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS)
    # Maybe this works as well, haven't tried yet.
    # set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS FALSE)
  else(BUILD_STATIC_EXECUTABLES)
    # Set RPATH to use for installed targets; append linker search path
    set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${LOFAR_LIBDIR}")
    set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
  endif(BUILD_STATIC_EXECUTABLES)

HTH,
Marcel Loose.




More information about the CMake mailing list