我是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
运行时未产生任何输出。源代码文件是
我的
extern int foo;
void print_foo();
void print_int(int);
my.cpp
#include "my.h"
#include <iostream>
void print_foo() {
std::cout << foo << '\n';
}
void print_int(int num) {
std::cout << num << '\n';
}
use.cpp
#include "my.h"
#include <iostream>
int main() {
std::cout<<"DSGFSGFSG"<< '\n';
foo = 7;
print_foo();
int i = 99;
print_int(i);
}
我看过其他类似的问题(如果看起来不太一样,则是在编译C ++程序时VS 2013中的链接时错误-B. Stroustrup使用C ++的PPP:第8章-Q1 Drill?),但是解决方案还没有没为我工作。问题是使用g ++进行编译还是我犯了更基本的错误?
全局变量foo
仅在头文件中声明。
extern int foo;
您还需要定义在它my.cpp
int foo;
该声明是一个承诺:“它存在于某处”。
该定义实际上为该变量保留了一些存储空间。
因此,您的链接器会抱怨,因为某些依赖于此承诺的代码需要访问此丢失的存储。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句