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

sca*_*ers 4 c++ g++ clang linker-errors

我是 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)
Run Code Online (Sandbox Code Playgroud)

我也试过使用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);
Run Code Online (Sandbox Code Playgroud)

我的.cpp

#include "my.h"
#include <iostream>

void print_foo() {
  std::cout << foo << '\n';
}

void print_int(int num) {
  std::cout << num << '\n';
}
Run Code Online (Sandbox Code Playgroud)

使用.cpp

#include "my.h"
#include <iostream>

int main() {

  std::cout<<"DSGFSGFSG"<< '\n';
  foo = 7;
  print_foo();

  int i = 99;
  print_int(i);

}
Run Code Online (Sandbox Code Playgroud)

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

pro*_*-fh 7

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

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

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

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