如何解决为什么“ extern”关键字不能在同一文件中工作?
请参见以下示例代码,了解如何使用“ extern”。当我在代码中使用extern关键字时,出现编译错误。请提出解决问题的方法。
#include<iostream>
extern int x;
extern int y;
extern int z;
int main(){
x = 10;
y = 15;
z = (x>y ? x: y);
std::cout<<z;
return 0;
}
错误消息:
example8.cpp:(.rdata$.refptr.z[.refptr.z]+0x0): undefined reference to `z';
example8.cpp:(.rdata$.refptr.y[.refptr.y]+0x0): undefined reference to `y';
example8.cpp:(.rdata$.refptr.x[.refptr.x]+0x0): undefined reference to `x';
F:\DEVC_workspace\collect2.exe [Error] ld returned 1 exit status
解决方法
extern int x;
告诉编译器:“我将在其他一些编译单元中为您提供int x
。请期待在链接时找到它。
因此,您需要另一个文件:
example8b.cpp
int x = 0;
int y = 0;
int z = 0;
,您需要在项目中链接这两个文件。
但是最重要的:
是什么让您选择将x
,y
和z
作为外部元素?
结束下面的讨论:
-
extern int x;
的意思是“某处会有x” -
int x;
的意思是“请在此处放置一个x
” -
undefined reference to x
的意思是“我没有找到您想要x出现的位置”
编译器需要放置x
的位置。您没有给出这样的位置,因为extern
专门要求编译器不要在其中放置x
。错误是编译器告诉您将x
放在某处。
疑虑已清除。解决的问题(代码编辑)
#include<iostream>
extern int x = 0;
extern int y = 0;
extern int z = 0;
int main(){
x = 10;
y = 15;
z = (x>y ? x: y);
std::cout<<z;
return 0;
}
或
#include<iostream>
extern int x;
extern int y;
extern int z;
int main(){
int x = 10;
int y = 15;
int z = (x>y ? x: y);
std::cout<<z;
return 0;
}
参考:
范例1:
extern int var;
int main(void)
{
var = 10;
return 0;
}
This program throws an error in compilation because var is declared but not defined anywhere. Essentially,the var isn’t allocated any memory. And the program is trying to change the value to 10 of a variable that doesn’t exist at all.
示例2:
#include "somefile.h"
extern int var;
int main(void)
{
var = 10;
return 0;
}
Assuming that somefile.h contains the definition of var,this program will compile successfully.
资料来源:geeksforgeeks:Link,由@Calculuswhiz建议
感谢@Jeffrey
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。