由于在 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 第 8 章末尾进行练习 "Programming and Practices using c++" 但是当我尝试编译时出现以下错误代码

➜  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 在 运行 时没有输出。源代码文件是

my.h

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

}

我查看了其他类似的问题(如果在 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;

声明是一个承诺:"it exists somewhere"。
定义实际上为这个变量保留了一些存储空间。

所以你的链接器抱怨是因为一些代码依赖于它 promise 需要访问这个丢失的存储空间。