• Re: [OT] Linking against a static library

    From Jack@Jack@invalid.invalid to comp.lang.c, comp.lang.c++ on Sun Aug 31 18:16:14 2025
    From Newsgroup: comp.lang.c++

    On 28/08/2025 17:12, pozz wrote:
    I don't think this is a pure C programming question, but it's related.

    I'm building a static library mylib.a with all the object files except main.o, and the final executable linking together main.o and mylib.a.

    I want to remove from the final exe everything present in mylib.a that
    is not used in main.o.

    Suppose only mod1.o is present in mylib.a. foo1() and bar1() are defined
    in mod1.c. main() is the only function in main.c and only foo1() is
    called from main().

    gcc -O2 -ffunction-sections -fdata-sections -c -o mod1.o mod1.c
    ar rcs mylib.a mod1.o
    gcc -O2 -ffunction-sections -fdata-sections -c -o main.o main.c
    gcc -Wl,--gc-sections,--print-gc-sections -o main[.exe] main.o mylib.a objdump -d main[.exe] | grep bar1

    MinGW in Windows build a main.exe that contains bar1(), while gcc in WSL doesn't.

    Why?


    I am not sure whether you are creating a DLL file for your library. I
    ask this because you mentioned "final exe" which implies Windows
    executable file that uses DLL file.

    Step 1 is to create and compile your library source code:

    // mycode.c
    #include <stdio.h>

    // Exported function
    __declspec(dllexport) void hello() {
    printf("Hello from DLL!\n");
    }


    Step 2: compile it like so:

    gcc -shared -o mydll.dll mycode.c


    Step 3: create a header file:
    // mycode.h
    #ifndef MYCODE_H
    #define MYCODE_H

    __declspec(dllimport) void hello();

    #endif

    Step 4: Create an import library for linking:

    gcc -c mycode.c
    gcc -shared -o mydll.dll mycode.o -Wl,--out-implib,libmydll.a


    Step 5: Create a client to use your DLL

    // main.c
    #include "mycode.h"

    int main() {
    hello();
    return 0;
    }


    Step 6: Compile client to create main.exe file:

    gcc main.c -L. -lmydll -o main.exe


    These are all commands in few lines:

    # Compile and create DLL
    gcc -c mycode.c
    gcc -shared -o mydll.dll mycode.o -Wl,--out-implib,libmydll.a

    # Compile and link client
    gcc main.c -L. -lmydll -o main.exe

    This should work but is a streamlined version for this discussion.

    Good luck.




    --- Synchronet 3.21a-Linux NewsLink 1.2