“-L -lmylib” 在 g++ 中未按预期工作。

huangapple go评论51阅读模式
英文:

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

问题

以下是翻译好的部分:

这是文件树:

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

这个命令不起作用:

g++ -L/home/xxx/make_test -lmylib  main.o -o myprogram2
/usr/local/bin/ld: main.o: 在函数 `main' 中:
main.cpp:(.text+0x9): 对 `f' 的引用未定义
collect2: 错误: ld 返回 1

但这个命令会起作用:

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

我不知道为什么会出现错误?-L/home/xxx/make_test -lmylib 已经包含了查找 libmylib.a 所需的所有信息。

这是全部的代码:

// 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
英文:

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

答案1

得分: 2

当使用静态库时,必须在列出任何依赖于该静态库的模块之后列出静态库。

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

请注意,libmylib.amain.o 之后列出。-l 选项必须遵循相同的规则:

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

-l 只是一个快捷方式,实际存在的是 libmylib.alibmylib.so 中的一个。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月27日 09:45:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定