我是 C++(以及一般编译语言)的新手,正在 Bjarne Stroustrup“使用 C++ 进行编程和实践”的第 8 章末尾进行练习,但是当我尝试编译代码时出现以下错误
➜ Desktop g++ -std=c++11 *.cpp -o use
Undefined symbols for architecture x86_64:
"_foo", referenced from:
print_foo() in my-4f7853.o
_main in use-46cb26.o
(maybe you meant: __Z9print_foov)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
我也试过使用
g++ -c my.cpp use.cpp
其次是 g++ -o use.exe my.o use.o
但这给出了同样的错误。我尝试的另一种方法是 g++ -c use.cpp -o use.exe
,然而 use.exe
运行时没有产生任何输出。源代码文件是我的.h
extern int foo;
void print_foo();
void print_int(int);
我的.cpp
#include "my.h"
#include <iostream>
void print_foo() {
std::cout << foo << '\n';
}
void print_int(int num) {
std::cout << num << '\n';
}
使用.cpp
#include "my.h"
#include <iostream>
int main() {
std::cout<<"DSGFSGFSG"<< '\n';
foo = 7;
print_foo();
int i = 99;
print_int(i);
}
我查看了其他类似的问题(如果看起来不一样,则在 Link-time errors in VS 2013 while compiling the C++ program - B. Stroustrup's PPP using C++: Ch. 8 - Q1 Drill? 中),但这些解决方案对我不起作用。问题与我使用 g++ 的编译有关还是我犯了一个更基本的错误?
最佳答案
全局变量 foo
仅在您的头文件中声明。extern int foo;
您还需要在 my.cpp
中定义它int foo;
声明是一个 promise :“它存在于某处”。
定义实际上为这个变量保留了一些存储空间。
所以你的链接器提示,因为一些代码依赖于此
promise 需要访问这个丢失的存储。
关于c++ - 由于在 Bjarne Stroustrup "Programming and Practices using c++"中找不到符号导致的链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60968882/