我正在从Programming Principles and Practices using C++ by Bjarne Stroustrup学习C ++。我在编译过程中遇到foo变量的麻烦。阅读extern关键字上的许多其他链接,但仍然无法找出问题所在。

//ch8d1_my.h

extern int foo;
void print_foo();
void print(int);

//ch8d1_my.cpp
#include "ch8d1_my.h"
#include "std_lib_facilities.h"

void print_foo()
{
  cout << "foo = " << foo << '\n';
}

void print(int i)
{
  cout << "i = " << i << '\n';
}


//ch8d1_use.cpp

#include "ch8d1_my.h"

int main()
{
 int foo = 7;
  print_foo();
  print(99);
 return 0;
}

Error: ch8d1_use.cpp: In function ‘int main()’:
ch8d1_use.cpp:5:6: warning: unused variable ‘foo’ [-Wunused-variable]
  int foo = 7;
      ^
/tmp/ccoVkK6R.o: In function `print_foo()':
ch8d1_my.cpp:(.text+0xb): undefined reference to `foo'
collect2: error: ld returned 1 exit status

最佳答案

include“ ch8d1_my.h” //这是错误的。应该在文件的开头
  
  include“ std_lib_facilities.h” //这是错误的。应该在


#include "ch8d1_my.h"
#include "std_lib_facilities.h"

extern int foo;
void print_foo();
void print(int);

//ch8d1_my.cpp
int foo = 7;       //You need to declare extern as global variable

void print_foo()
{
  cout << "foo = " << foo << '\n';
}

void print(int i)
{
  cout << "i = " << i << '\n';
}


//ch8d1_use.cpp

#include "ch8d1_my.h"

int main()
{
  print_foo();
  print(99);
 return 0;
}

关于c++ - 具有多个文件的extern关键字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29367932/

10-12 21:51