[英]Why is extern required for forward declaration of global variables but not for functions when using them from other files in C++
From what I already know, both global non-constant variables and functions have external linkage by default.据我所知,全局非常量变量和函数默认都具有外部链接。 So they can be used from other files with the help of forward declaration.
因此它们可以在前向声明的帮助下从其他文件中使用。 For example:
例如:
<other.cpp> <其他.cpp>
int myNum{888};
int getAnInt()
{
return 999;
}
<main.cpp> <主.cpp>
#include <iostream>
extern int myNum; // "extern" keyword is required.
int getAnInt(); // "extern" keyword is NOT required.
int main()
{
std::cout << getAnInt() << "\n";
std::cout << myNum << "\n";
}
However, if no extern
before int myNum;
但是,如果在
int myNum;
之前没有extern
; . . This will happen:
这将发生:
duplicate symbol '_myNum' in:
/path~~/main.o
/path~~/other.o
ld: 1 duplicate symbol for architecture x86_64
So my question is why extern
is required for myNum
?所以我的问题是为什么
myNum
需要extern
? Don't global non-constant variables have external linkage by default?全局非常量变量不是默认有外部链接吗?
Because there is a difference between因为两者之间存在差异
int getAnInt();
and和
int getAnInt() { ... }
Namely the brackets themselves, and as such there is no need for a marker like extern
to differentiate between the two.即括号本身,因此不需要像
extern
这样的标记来区分两者。
Particularly, the former is a declaration, which just states that getAnInt
exists and returns an int
etc, whereas the latter gives it its definition.特别是,前者是一个声明,它只是声明
getAnInt
存在并返回一个int
等,而后者给出了它的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.