考虑这段 C 代码:
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
bool foo(int a, int b, int c, int d) {
double P = atan2(a, b);
double Q = atan2(c, d);
return P < Q;
}
bool bar(int a, int b, int c, int d) {
return atan2(a, b) < atan2(c, d);
}
int main() {
if (foo(2, 1, 2, 1)) puts("true"); else puts("false");
if (bar(2, 1, 2, 1)) puts("true"); else puts("false");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我用 编译它时gcc -lm -m64
,它会打印
false …
Run Code Online (Sandbox Code Playgroud) 我遇到了GCC的问题.它无法找到我的全局变量.我创建了一个示例C++项目来隔离问题:
a.cpp:
#include "b.h"
const char * const g_test = "blah blah";
int main(){
test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
b.cpp:
#include <iostream>
#include "a.h"
using namespace std;
void test(){
cout << g_test;
}
Run Code Online (Sandbox Code Playgroud)
啊:
extern const char * const g_test;
Run Code Online (Sandbox Code Playgroud)
BH:
void test();
Run Code Online (Sandbox Code Playgroud)
我这样编译:
$ g++ -o a.o -c a.cpp
$ g++ -o b.o -c b.cpp
$ g++ -o test a.o b.o
b.o: In function `test()':
b.cpp:(.text+0x7): undefined reference to `g_test'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
在最后一个命令中更改目标文件的顺序不会改变任何内容.
为什么链接器会抛出错误?我本来希望只是创建一个可执行的打印"blah blah",但不知怎的错误出现了.我认为没有任何理由会失败.