繁体   English   中英

由于在 Bjarne Stroustrup “Programming and Practices using c++”中找不到符号导致的链接错误

[英]Linking Error due to symbol(s) not found in Bjarne Stroustrup "Programming and Practices using c++"

我是 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);

}

我看过其他类似的问题(如果看起来不一样,编译 C++ 程序时 VS 2013中的链接时错误 - B. Stroustrup's PPP using C++: Ch. 8 - Q1 Drill? )但解决方案没有对我没用。 问题与我使用 g++ 的编译有关还是我犯了一个更基本的错误?

全局变量foo仅在您的头文件中声明
extern int foo;

您还需要在my.cpp定义
int foo;

声明是一个承诺:“它存在于某处”。
定义实际上为这个变量保留了一些存储空间。

所以你的链接器抱怨,因为一些依赖这个承诺的代码需要访问这个丢失的存储。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM