C/C++语言标准当中,有没有所谓强符号,弱符号的感念?

pqepqeisd 2015-11-07 05:15:44
还是实现者的一种概念?

gcc编译c程序,未初始化的符号并没有成为弱符号啊
<<程序员的自我修养>>这本书上提到,对于gcc而言,程序中定义了但是没有初始化的符号就是弱符号,可以被强符号(定义并初始化)覆盖
于是做了一个实验:

$ cat x.c
int i=20;

$ cat main.c
#include<stdio.h>
int i;
int main()
{
printf("%d\n",i);
return 0;
}

却是是这样,而且这个仅对后缀名是.c的文件生效,.cpp就不起作用。
这个规则是gcc自己的呢,还是C/C++标准本身也提到了一些链接的规则?
谢谢。
...全文
111 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
fefe82 2015-11-07
  • 打赏
  • 举报
回复
强符号 弱符号 不是 C 或 C++ 的概念。这是实现 C 或 C++ 的链接规则的一种实现。 C/C++ 标准将符号的链接属性分为三种,external linkage, internal linkage, no linkage。 不同编译单元(文件)中的具有 external linkage 的相同符号代表同一个对象。 具有 external linkage 的符号在同一个程序(program)(可以包含多个源文件)里,只能有一个 definition 。 ============== 但是,关于什么是 definition ,C 与 C++ 的不同叙述产生了不同的效果: C11 n1570 6.7 Declarations 5 A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that: — for an object, causes storage to be reserved for that object; — for a function, includes the function body;119) — for an enumeration constant, is the (only) declaration of the identifier; — for a typedef name, is the first (or only) declaration of the identifier. C++14 n2496 3.1 Declarations and definitions 2 A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a functionbody, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attributedeclaration (Clause 7), an empty-declaration (Clause 7), a using-directive (7.3.4), an explicit instantiation declaration (14.7.2), or an explicit specialization (14.7.3) whose declaration is not a definition. int a; 在 C 里可能不是一个 definition (也可以是),但是在 C++ 里它一定是一个 definition 。 所以你的程序在 C 模式下可以编译,但是在 C++ 下就产生了重定义的错误。 ============== 猜想一下强符号 / 弱符号的作用: 在 C 里,编译器可以在不同文件的 int a; 的声明里任意选择一个作为定义,强符号/弱符号可以帮助编译器做出这一选择:强符号一定是一个定义,弱符号则可能不是一个定义。

64,691

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧