gcc functions with constructor attribute are not being linked

Viewed 4956

I have a bunch of static libraries and they are interdependent. I faced problems while linking those libraries for my target because of dependencies. As a workaround I created one single archive file from all the libraries.

One of the static library has constructor and destructor functions so does the combined archive (examined the archive using nm and objdump) But when I used the combined archive for my target the final binary does not contain the constructor and destructor functions.

I also tried with --whole-archive but this option doesn't seem to work for me (the binary size didn't increase).

Any ideas what might have gone wrong. Thank you

2 Answers

From the other answer:

You can force the linker to include the module by explicitly linking with the object file that corresponds to the source containing the constructor/destructor functions.

With modern CMake, this is as easy as an INTERFACE source on the library. Just use a dedicated source file for the constructor.

cmake_minimum_required(VERSION 3.13)

add_library(mylib STATIC libsource.c)
target_sources(mylib INTERFACE lib_ctor.c)
# CMake prior 3.13 requires an absolute path
# target_sources(mylib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/lib_ctor.c)

add_executable(prog app.c)
target_link_libraries(prog mylib)

Here, lib_ctor.c would contain the constructor. INTERFACE sources are added to the list of source files of every target linking against mylib. So they get explicitly linked and the constructor function is read by the linker.

I wasted an hour or two on --whole-archive and other hacks before realizing my build system can take care of this in a much cleaner way. As CMake is pretty popular nowadays and this is the top search result for terms like "gcc force constructor" and "gcc constructor not linked", I'd like to share it.

Related