C中const的外部链接 [英] External linkage of const in C

查看:94
本文介绍了C中const的外部链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我遇到这种奇怪的行为时,我正在使用 extern 关键字 in C
我有两个文件:

I was playing with extern keyword in C when I encountered this strange behaviour. I have two files:

file1.c

#include<stdio.h>
int main()
{
    extern int a;
    a=10;
    printf("%d",a);
    return 0;
}

file2.c

const int a=100;

当我一起编译这些文件时,没有错误或警告,并且在运行它们时,输出设为 10 。我曾希望编译器在 a = 10; 行上报告错误。

When I compile these files together, there is no error or warning and when I run them, output comes to be 10. I had expected that the compiler should report an error on line a=10;.

此外,如果我更改file2.c的内容为

Moreover, if I change the contents of file2.c to

const int a;

也就是说,如果删除全局const变量 a的初始化然后编译文件,仍然没有错误或警告,但是当我运行它们时,会出现分段错误。

that is, if I remove the initialization of global const variable a and then compile the files, there is still no error or warning but when I run them, Segmentation Fault occurs.

为什么会出现这种现象?它被归类为不确定的行为吗?

Why does this phenomenon happen? Is it classified under undefined behaviour? Is this compiler- or machine- dependent?

PS:我已经看到很多与此相关的问题,但是要么是C ++的,要么是他们讨论

PS: I have seen many questions related to this one, but either they are for C++ or they discuss extern only.

推荐答案

编译和链接是两个不同的阶段。在编译过程中,单个文件将被编译为目标文件。编译器会发现file1.c和file2.c在内部是一致的。在链接阶段,链接器只会将所有出现的变量 a 指向相同的存储位置。这就是您看不到任何编译或链接器错误的原因。

Compilation and linking are two distinct phases. During compilation, individual files are being compiled into object files. Compiler will find both file1.c and file2.c being internally consistent. During linking phase, the linker will just point all the occurrence of the variable a to the same memory location. This is the reason you do not see any compilation or linker error.

为完全避免您提到的问题,建议将extern放在头文件中然后将该头文件包含在其他C文件中。这样,编译器可以捕获标头和C文件之间的任何不一致之处。

To avoid exactly the problem which you have mentioned, it is suggested to put the extern in a header file and then include that header file in different C file. This way compiler can catch any inconsistency between the header and the C file

下面的stackoverflow也谈到了链接器无法对外部变量进行类型检查。

The following stackoverflow also speaks about linker not able to do type checking for extern variables.


类似地,全局变量的类型(以及类的静态成员和等等)不会被链接程序检查,因此如果您声明extern int test;在一个翻译单元中定义浮动测试;在另一种情况下,您会得到不好的结果。

Similarly, the types of global variables (and static members of classes and so on) aren't checked by the linker, so if you declare extern int test; in one translation unit and define float test; in another, you'll get bad results.

这篇关于C中const的外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆