How to make GCC to compile so that binary uses the new shared object?

Viewed 60

My program has two C files. One of them is a library that the other one uses. When I change the library and run the executable file, it does not use the new library. The following are the codes.

main1.c

#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include "lib.c"

int main()
{
    int x = 0;
    while (true) {
        printf("%d\n", x);
        sleep(1);
        x = func(x);
    }
    return 1;
}

lib.c

int func(int x)  
{                
    return x + 1;
}                

I compile the library file using this command.

gcc -fPIC -MMD -shared -o libfunc.so -c lib.c

And compile the main file using this command.

gcc -fPIC -MMD -dynamic -L./ -lfunc main1.o

Now I change the library file to the following.

New lib.c

int func(int x)  
{                
    return x - 1;
}                

I compile it again using this command.

gcc -fPIC -MMD -shared -o libfunc.so -c lib.c

Now when I run the binary file, I still see the output of the old library. How could I change my GCC commands, so that the binary loads the library file when it wants to run?

$ ./a.out
1
2
^C
$
1 Answers

Declare the function instead of including the implementation by changing:

#include "lib.c"

to:

int func(int x);

Then you just build the library and binary:

gcc -fPIC -shared libfunc.c -o libfunc.so
gcc main1.c -lfunc -o main1

and running it will report:

0
1
2
...

To demonstrate that it uses the new library change libfunc.c to increment by 2 and only rebuild the library as above. It will now return:

0
2
4
...

I have LD_LIBRARY_PATH=. so it picks up the library from the current directory.

Related