48

I have a shared library (*.so) created using Real View Compiler Tools (RVCT 3.2) on windows target. Then I try to link this *.so file with my application using gcc on linux system.

What is the gcc option to link this shared library with my application linux?

My question is, is the -shared option, which is used as

gcc -shared myfile.so

..., used to create the SO file or to link the SO file? I believe it creates something like:

gcc -lmyfile.so

Is this enough? Or is there any other switch to tell the linker that it's a dynamic library (shared object)?

goldenmean
  • 18,376
  • 54
  • 154
  • 211

2 Answers2

61

What worked for me was:

gcc -L. -l:myfile.so
mluc
  • 771
  • 6
  • 3
  • 8
    -L{path to file containing library} -l${library name} if I have a library named libmine.so in /home/newhall/lib/ then I'd do the following to link it into my program: $gcc -o myprog myprog.c -L/home/newhall/lib -lmine [Reference Site](https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_C_libraries.html) – Gowrav Feb 11 '18 at 07:32
  • 21
    For those wondering about the colon, it gets the linker to look for a file with the exact name specified, instead of looking for variations on the name. See https://stackoverflow.com/a/48540643/1175455. – Harry Cutts Sep 11 '18 at 18:27
  • 1
    Is there any difference between a dynamic library (.so) and a static library (.a) while linking ? I always thought that dynamic libraries were only used at run time and not a compilation time. Did I miss something ? – Bemipefe Feb 08 '19 at 14:40
  • This says "undefined reference" but it is defined in the file. Why? – circl Dec 28 '21 at 18:21
  • /usr/bin/ld: cannot find -l:/ – CS QGB Nov 03 '22 at 02:19
27

gcc -lmyfile should be enough (provided that your library is named libmyfile.so). The linker searches for shared objects when possible and AFAIK prefers them.

jpalecek
  • 47,058
  • 7
  • 102
  • 144
  • I have a related question: In case my library libmyfile.so is a symlink to libyourfile.so, will linking my program using gcc -lmyfile still work? (I need to maintain backward compatibility of certain clients which are are unaware of the library name change.) – baskin Jan 14 '10 at 09:42
  • 3
    @jpalecek Does it work if the file name has the extension .dll? – mrk Sep 24 '12 at 17:11
  • 1
    What if the library not in `/usr/bin/ld`? – Dragos Rizescu Nov 25 '13 at 13:54
  • 3
    Add option `-L/path/to/so/folder/` to add search folder for `.so` – Diederik Feb 05 '14 at 14:24
  • I tried to link `libraryName.dll` in Eclipse CDT, however it couldn't link when I specified full file name - it only works when specified filename WITHOUT extension: `libraryName`. So the linker option is `-llibraryName`. – Danijel Nov 17 '16 at 08:25
  • what if we have 2 different versions of myfile lib and want to attach only one of them? How do we do that? – ABD Sep 28 '22 at 10:26