Search code examples
c++gcccompiler-errors

"-L -lmylib" is not working as expected in g++


Here is the file tree:

├── lib
│   ├── mylib.cpp
│   ├── mylib.h
│   └── mylib.o
├── libmylib.a
├── main.cpp
├── main.o
├── Makefile
├── mylib
├── mylib.a
└── myprogram

This cmd not work

g++ -L/home/xxx/make_test -lmylib  main.o -o myprogram2
/usr/local/bin/ld: main.o: in function `main':
main.cpp:(.text+0x9): undefined reference to `f'
collect2: error: ld returned 1 exit status

But this will work:

g++ main.o libmylib.a -o myprogram    

I don't know why the error happens? -L/home/xxx/make_test -lmylib has covered all the info to find libmylib.a.

There is all the code:

# main.cpp
#include "lib/mylib.h"
int main(){
    f();
    return 0;
}
# mylib.cpp
#include "mylib.h"

int f(){
    return 1;
}

int b(){
    return 2;
}
#mylib.h
#ifndef MAKE_TEST_MYLIB_H
#define MAKE_TEST_MYLIB_H

extern "C" int f();
extern "C" int b();
#endif //MAKE_TEST_MYLIB_H

Solution

  • When static libraries are used, static libraries must be listed after any modules whose dependencies must be satisfied by that static library.

    g++ main.o libmylib.a -o myprogram
    

    Note that libmylib.a is listed after main.o. The -l option must follow the same rule:

    g++ -L/home/xxx/make_test main.o -lmylib -o myprogram2
    

    -l is just a shortcut for either libmylib.a or libmylib.so, whichever one actually exists.