cgccshared-librarieslto

gcc LTO - shared library - Am I right?


Context :

Trying to understand how lto (link time compilation) works

Code:

I have those files :

julia.h:

#ifndef JULIA_H
#define JULIA_H
#include <stdio.h>
int julian();

#endif // JULIA_H

julia.c :

#include "julia.h"

int julian()
{
    printf("Hello Worldu!\n");
    return 0;
}

compiled as a shared library like so : gcc -O3 -fPIC -shared julia.c -o libjulia.so -L$PWD -I$PWD -flto

and my main program :

main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "julia.h"

int main()
{

    julian();

    return 0;
}

compiled with : gcc -O3 main.c -I/path/to/inc -L/path/to/lib -Wl,-rpath=/path/to/lib -ljulia -flto

It compiles fines.

Question :

So, this is a hello world program but am I doing it right with LTO ? Is is all it takes to optimize the linkage ?

Thanks


Solution

  • LTO doesn't affect shared libraries; they're being linked with by dynamic linker, which is not aware of LTO and can't modify code at runtime.

    Moreover, LTO doesn't even work with static libraries, but some day it presumably will (it is TODO on gcc wiki).

    But yes, what it takes to enable is using -flto on both compilation and linking phases.