我有三个文件:
我的.cpp
#include "my.h"
#include <iostream>
void print_foo() {
cout << foo << 'n';
}
void print(int i) {
cout << i << 'n';
}
我的.h
extern int foo;
void print_foo();
void print(int);
使用.cpp
#include "my.h"
int main(int argc, char *argv[]) {
foo = 7;
print_foo();
print(99);
return 0;
}
现在当我运行g++ my.cpp use.cpp
时出现错误
/usr/bin/ld: /tmp/ccUKJUlZ.o: in function `print_foo()':
my.cpp:(.text+0x6): undefined reference to `foo'
/usr/bin/ld: /tmp/ccN0mIhY.o: in function `main':
use.cpp:(.text+0x11): undefined reference to `foo'
collect2: error: ld returned 1 exit status
此外,如果我运行g++ -c my.cpp
一切正常,但是,如果我运行g++ my.o use.cpp
,我会收到同样的错误。
你从来没有真正定义过一个变量foo
- 在use.cpp
和my.cpp
中,你使用foo
,在my.h
中你声明为一个extern
。
有关声明与定义的详细信息,请参阅此响应的开头。您可能认为,如果您在use.cpp
中的foo = 7
行前面添加一个类型,您的问题就会得到解决;但是,您还需要做的是将foo
变成全局变量而不是局部变量(当您仅在main
中声明它时(,因为extern
只会"查找"具有全局范围的变量。您可以通过在任何函数外部声明变量来使变量成为全局变量(旁注 - 您应该只在绝对必要时才使用全局变量(。
因此,您可以通过将use.cpp
更改为以下内容来解决问题:
#include "my.h"
int foo = 7;
int main(int argc, char *argv[]) {
print_foo();
print(99);
return 0;
}