使用extern int的LNK2001错误 [英] LNK2001 error using extern int
问题描述
我有一个简单的示例,我无法编译它:
I have this simple example and I can't get it to compile:
三个文件: my.h , my.cpp 和 use.cpp :
//my.h
extern int foo;
void print_foo();
void print(int);
//my.cpp
#include "my.h"
#include "../../stb_lib_facilities.h" //inlcudes cout, cin, etc
void print_foo(){
cout << foo << endl;
}
void print(int i){
cout << i << endl;
}
//use.cpp
#include <iostream>
#include "my.h"
int main(){
foo = 7;
print_foo();
print(99);
return 0;
}
当我尝试编译它时,我收到三个错误:LNK2001:extern"int foo" ..LNK2019:extern"int foo" ..LNK1120:
When I try to compile it I get three errors: LNK2001: extern "int foo".. LNK2019: extern "int foo".. LNK1120:
我做错了什么?谢谢您的帮助
What am I doing wrong? Thanks for any help
推荐答案
您没有全局变量的任何定义.在任何 .cpp
文件中,但仅在其中一个文件中,您应该添加以下内容:
You do not have any definition of your global variable. In any of your .cpp
files, but just in one of them, you should add this:
int foo = 0; // This is a definition
您的声明:
extern int foo; // This is a declaration
仅告诉编译器存在这样的全局变量,但是实际上没有地方可以定义它.因此,链接器最终会抱怨您有一个未定义的引用符号.
Only tells the compiler that such a global variable exists, but then there is no place where you actually define it. Therefore, the linker will eventually complain that you have an undefined referenced symbol.
这篇关于使用extern int的LNK2001错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!