gpt4 book ai didi

c++ - 下面的函数有什么联系?

转载 作者:行者123 更新时间:2023-11-30 03:00:16 25 4
gpt4 key购买 nike

当我阅读 c++ 03 标准(7.1.1 存储类说明符 [dcl.stc])时,有一些示例如下,我无法判断每个连续声明的链接是如何确定的?有人可以帮忙吗?提前致谢!

static char* f();    // f() has internal linkage
char* f()
{ /* ... */ } // f() still has internal linkage

char* g(); // g() has external linkage
static char* g()
{ /* ... */ } // error: inconsistent linkage

void h();
inline void h(); // external linkage

inline void l();
void l(); // external linkage

inline void m();
extern void m(); // external linkage

static void n();
inline void n(); // internal linkage

static int a; // a has internal linkage
int a; // error: two definitions

static int b; // b has internal linkage
extern int b; // b still has internal linkage

int c; // c has external linkage
static int c; // error: inconsistent linkage

extern int d; // d has external linkage
static int d; // error: inconsistent linkage

UPD:另外,我怎样才能理解标准中的声明,

The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same object name or the same overloading of a function name shall imply the same linkage. Each function in a given set of overloaded functions can have a different linkage, however.

最佳答案

除非您对在全局范围内声明的独立函数或变量使用 static,否则它们将具有外部链接

请注意,在函数上使用关键字 inline 不会更改函数的链接。

另一个需要注意的重点是 const 变量在 C++ 中具有内部链接,这与 C 不同。


The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same object name or the same overloading of a function name shall imply the same linkage. Each function in a given set of overloaded functions can have a different linkage, however."

一个声明向编译器引入了一个标识符,这样编译器就可以知道它的类型。在C++中,一个标识符可以被声明任意多次,例如:

void doSomething(int, double);         // External Linkage
extern void doSomething(int, double); // External Linkage is explicitly mentioned

引用的段落意味着相同标识符的所有此类声明都应指定相同的链接。例如,以下是无效的:

void doSomething(int, double);        //External Linkage
static void doSomething(int, double); //Internal Linkage due to static

同时,同一函数的重载版本可以有不同的链接,因此以下是有效的:

void doSomething(int, double);
extern void doSomething(int, double);
void doSomething(double,int);

关于c++ - 下面的函数有什么联系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12256440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com