Search code examples
cstatic-linkingobject-files

Adding a common header/object file that is used by other object files


I have created a http library which contains 2 object files (web.o & webssl.o). These two files share some common constants and functions, that must be repeated for each file. Which also means that I need to update both files when changes are made.

I would like to have a webcommon.o file that I can link to the web.o and webssl.o files. It will contain all the common code that both libraries shares.

I created the webcommon.o file with the shared code. I removed the shared code from web.c and webssl.c. When I go to compile web.c and webssl.c with this:

# gcc -Wall -Werror -O3 -c web.c /my/lib/webcommon.o;
gcc: warning: /my/lib/webcommon.o: linker input file unused because linking not done

Through searching, it appears that the -c option ignores the linking of object files.

How do I create a webcommon.o object file that is used with web.o and webssl.o? Right now it looks like my only 2 options are:

  1. Keep the duplicate code in the web.o and webssl.o and update both files when needed.

  2. Make sure I add the webcommon.o file when compiling a program a program with either web.o or webssl.o


Solution

  • If it is acceptable for webssl.o to have a link dependency on web.o, then you can just have webssl.o declare the shared variables extern, without defining them. When you link a program with webssl.o and web.o, webssl.o will share those extern variables, and webssl.o will have access to the functions in web.o.

    This sort of thing is usually done by creating a header containing prototypes of all the shared functions and extern declarations of all the shared variables. All source files sharing those things include the header, but each shared entity is defined in only one source file. Defining a file-scope variable means providing a declaration with an initializer; defining a function means providing the function body.

    If you applied this approach, putting all the definitions in the 'web' module, then web.o could be used on its own, but webssl.o could only be used together with web.o.

    Alternatively, if you only use web.o and webssl.o independently of each other, then you could build a static library for each that includes webcommon.o as well. That is,

    • one lib (e.g. libweb.a) containing web.o and webcommon.o, and
    • one lib (e.g. libwebssl.a) containing webssl.o and webcommon.o

    You then link the appropriate static library to your programs, instead of linking web.o or webssl.o directly.