0

I'm trying to link my C program to both a static and dynamic library to see the difference. How do I do that? I've made my own Makefile:

# ------ executable rule  -----------
app : app.o
        -gcc -g  app.o -o app

# ------ intermeditate object files rule (.o) -------
app.o : main.c
         -gcc -g -c main.c -o app.o

I've only shown you some of my Makefile as I think the rest is unnecessary.
I've tried to write -L. lstatic after -gcc -g app.o -o app but it didn't work.

klutt
  • 30,332
  • 17
  • 55
  • 95
Hudhud
  • 7
  • 4
  • 1
    Either use `-static` or explicitly pass in the file you want to link against just like you would a ".o" file. [Also, read the manual](https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html) – Brian McFarland Feb 16 '16 at 19:43
  • And if I want to link it to a dynamic library then I've to write `-gcc -g app.o -o app -rdynamic` ? – Hudhud Feb 16 '16 at 19:56
  • 2
    No. Dynamic linking is the default. So leave out `-static` will do. When linking without `-static` the linker (at least gnu) will first look for the dynamic library and if it doesn't find that it will then look for the static library. – kaylum Feb 16 '16 at 19:59
  • 1
    As far as "seeing the difference": Under most Linux distros, you can use `ldd`, `readelf -d`, or `file` on your resulting binary to tell you if its dynamically or statically linked. – Brian McFarland Feb 16 '16 at 21:01

1 Answers1

0

Read about invoking GCC. Order of arguments to gcc matters a lot!

You could use -static or -Bstatic

You can also explicitly link with static libraries, by giving some /usr/lib/libfoo.a (or some appropriate file path) argument at link time.

You'll better improve your Makefile to use existing builtin rules (try make -p) and conventional variables, e.g. like here. Read the documentation of GNU make.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547