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

标签 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)

我也试过使用 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/

相关文章:

c++ - std::hex/std::oct 不工作(打印十进制值)

c++ - 使用 Fortran 编译和链接 C++

c++ - 在长数组中查找唯一元素会导致段错误?

c++ - 使用g++编译Objective-C项目时出现运行时错误

c++ - 如何在 clang 库中执行模板替换?

C++ 链表 - 使用哨兵从文件中读取数据

c++ - 模板函数不会编译

c++ - 抑制 -Wtautological-compare 警告

c++11 - 如何处理由空模板参数包扩展引起的未使用警告?

c++ - 三个显式向上转换到私有(private)基类的区别