gcclinkerelfconditional-compilation

Generating Multiple Object Files from one Source File


Question

Is it possible to create multiple objects from a single source file, ideally by ELF section? I know this is doable via external tooling after the fact via elfutils and friends but, unfortunately, I am stuck in a managed build environment and introducing new tooling mid-build is prohibitively complex (for now, at least).

Additional Information

This is ultimately for some dynamic symbol manipulation similar to U-Boot's command registration or Linux's initcall mechanism. To assist with this, I have created the usual __attribute__((used,section="")) macro to generate these symbols in a known section. Unfortunately, the managed build environment forces an intermediate static library which causes my generated symbols to be dropped as they are unreferenced in the main binary.

I know about -Wl,-whole-archive but I would prefer not to have to run this on my whole archive as this is an embedded project and space is at a premium. Thus, I am hoping I can break out all of the dynamic symbols form the known section and conglomerate them into a single object which will form its own archive which can then be included completely without space penalty.

I also know about --undefined but I don't know the specific symbol names ahead of time so I don't see how this would work without a ton of brittle extra parsing. Additionally, I am stuck on a SoC-provided toolchain of GCC 8.4.0 which doesn't support any kind of globbing like LLVM does.


Solution

  • Is it possible to go the other way and create multiple objects from a single source file

    That is very common (but not in a single compiler invocation):

    // x.c
    #ifndef FOO
    #define FOO Foo
    #endif
    int FOO() { return 42; }
    
    gcc -c x.c -o foo.o
    gcc -c x.c -DFOO=Bar -o bar.o
    gcc -c x.c -DFOO=Baz -o baz.o
    

    If you meant "multiple object files in a single compiler invocation", then no -- I know of no compiler that would do that.