0

I have built and installed my library according to the following cmake:

install(
    TARGETS ${LIBRARY_NAME}
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)

install(
    TARGETS ${LIBRARY_NAME}_static
    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)

so I get:

/usr/local/pkgconfig/libmylib.pc
/usr/local/lib/libmylib.0.1.1.dylib
/usr/local/lib/libmylib.0.dylib
/usr/local/lib/libmylib.dylib
/usr/local/lib/libmylib.a
/usr/local/include/libmylib.h

Now if I try to build test.c:

#include <libmylib.h>
int main() {
    mylibfoo();
}
  • gcc test.c -lmylib the source is compiled with the dynamic library.

else

  • gcc test.c the linker gives the following error:
Undefined symbols for architecture x86_64:
  "_mylibfoo", referenced from:
      _main in mylibfoo-a8b267.o

I'm trying on the Darwin Kernel Version 19.3.0 (MacOS) system but I get the same result on a Linux system unless I build with: gcc test.c -l:libmylib.a

I want that if -l was not specified, the build uses the static library.

Phocs
  • 2,430
  • 5
  • 18
  • 35
  • How would your program know about the external symbols (e.g. `_mylibfoo`) if you don't link them? – Kevin Mar 25 '20 at 11:43
  • 1
    "I want that if `-l` was not specified, the build uses the static library." - You cannot (unless you modify the compiler/linker). If you want to link with a library, then you need tell the linker about that. BTW, CMake is unrelated to your problem: it just creates and installs specific files. As you want to use these files outside of CMake project, with a plain compiler/linker, exactly this compiler/linker decides how the files will be used. – Tsyvarev Mar 25 '20 at 11:44
  • So new question, how does the compiler/linker find libc libraries like `stdio.h`, `stdlib.h` etc? I know they are dynamic libraries but it's not necessary to specify `-llibc`. – Phocs Mar 25 '20 at 11:56
  • In any case, how do I on the MacOS system tell the linker to use the static library? `-l:libmylib.a` does not work as on Linux – Phocs Mar 25 '20 at 11:58
  • "it's not necessary to specify `-llibc`" - `libc` is a part of the **compiler's implementation**, so the compiler/linker is aware about it and links it by default. Your library is not a part of the compiler implementation, so it cannot be linked automatically. "how do I on the MacOS system tell the linker to use the static library?" - Use full path to the library. See e.g. https://stackoverflow.com/questions/844819/how-to-static-link-on-os-x or https://stackoverflow.com/questions/4576235/mixed-static-and-dynamic-link-on-mac-os – Tsyvarev Mar 25 '20 at 12:32
  • You can also use RPATHs on unixoide OS. – at-2500 Apr 03 '20 at 06:14

0 Answers0