由于在Bjarne Stroustrup“使用c ++进行编程和实践”中找不到符号而导致的链接错误

问题描述 投票:0回答:1

我是C ++(和一般的编译语言)的新手,正在Bjarne Stroustrup“使用c ++的编程和实践”第8章的末尾进行演练,但是当我尝试编译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.cppg++ -o use.exe my.o use.o,但这给出了相同的错误。我尝试的另一种方法是g++ -c use.cpp -o use.exe,但是use.exe运行时未产生任何输出。源代码文件是

my.h

  1 extern int foo;
  2 void print_foo();
  3 void print_int(int);

my.cpp

  1 #include "my.h"
  2 #include <iostream>
  3
  4 void print_foo() {
  5   std::cout << foo << '\n';
  6 }
  7
  8 void print_int(int num) {
  9   std::cout << num << '\n';
 10 }

use.cpp

  1 #include "my.h"
  2 #include <iostream>
  3
  4 int main() {
  5
  6   std::cout<<"DSGFSGFSG"<< '\n';
  7   foo = 7;
  8   print_foo();
  9
 10   int i = 99;
 11   print_int(i);
 12
 13 }

我看过其他类似的问题(Link-time errors in VS 2013 while compiling the C++ program - B. Stroustrup's PPP using C++: Ch. 8 - Q1 Drill?中似乎不太一样),但是解决方案对我而言不起作用。是与使用g ++进行编译有关的问题,还是我犯了更基本的错误?

c++ g++ clang linker-errors
1个回答
2
投票

全局变量foo仅在头文件中已声明

© www.soinside.com 2019 - 2024. All rights reserved.