我正在从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
答案 0 :(得分:2)
包括“ch8d1_my.h”//这是错误的。应该在文件的开头
包含“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;
}