0

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
syheliel
  • 151
  • 1
  • 7
  • When linking with libraries, the order in which you link with the object files and libraries matter. Always add the libraries *last* on the command line. The reason is, when you put it first, there's no one that depends on or uses any of the function from the libraries yet, so it's simply disregarded. – Some programmer dude Feb 27 '23 at 01:51

1 Answers1

2

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148