gpt4 book ai didi

C 语法 : Is the following 'extern volatile const' behavior consistent among C compilers?

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:56 24 4
gpt4 key购买 nike

我做了如下的C实验:我有三个文件(a.ca.hb.c):

  • a.c:

    #define _A_C_
    #include "a.h"
    #undef _A_C_

    #include <stdio.h>

    int v = 19; // some value
    void
    fa()
    {
    printf("a.c: v = %d\n", v);
    }
  • a.h:

    #ifndef _A_H_
    #define _A_H_

    #ifndef _A_C_
    // before edit the following line was 'extern const int v;'
    extern volatile const int v;
    #endif

    void
    fa();

    #endif
  • b.c:

    #include "a.h"
    #include <stdio.h>

    void
    fb()
    {
    printf("b.c: v = %d\n", v);
    //v = 5; // -> uncomment this and you will get a compile error
    }

    int
    main()
    {
    fa();
    fb();
    getch();
    return 0;
    }

我想用它获得的是能够有选择地修改变量。

所以基本上,对于 a.cv 将被视为 int,对于其余部分,将被视为 const int代码(例如 b.c)。

GCC 4.8.1 中,此链接和行为符合预期

我想知道我是否可以跨 C 编译器依赖此行为。

谢谢

编辑

感谢 Pascal Cuoq,我意识到 a.h 中的 extern const int v; 需要修改为 extern volatile const int v; 以避免编译器优化问题

其他事实

  • 其中 extern const x 在句法上是有效的,const x 将导致 x 在生成的目标文件中作为符号导出
  • 因此,另一个等价的问题实际上是:在任何情况下,导出的符号 const int x 在生成的目标文件中 是否与 int x 不同? (例如,COFF 是否允许这样做?)

最佳答案

v will be seen as int for a.c and as const int for the rest of the code (e.g. b.c).

考虑函数:

extern int v = 5;

int main()
{
f();
return v;
}

GCC 会很乐意将上面的函数优化为 { f();返回 5; }。如果 f() 来自 v 不是 const 的文件并且实际上修改了 v,函数 main() 将不会按预期运行。

所以总而言之,它是标准不允许的,实际上它在实践中破坏了程序。

编辑:如果您希望不为 const 声明提供初始值设定项会有所帮助,请考虑以下事项:

$ cat o.c
extern const x;

main(){
int y = x;
f();
y -= x;
return y;
}

$ gcc -O3 -S o.c
$ cat o.s
...
main:
...
call f
xorl %eax, %eax /* This sets the return value of main. To zero. Hardcoded. */
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc

实际上,汇编文件中根本没有对x 的引用。它可以与其他文件链接,其中一个文件提供了 f,并且永远不会提示 x 丢失,更不用说它的类型错误了。

链接器不是静态分析器。它不是用来检测错误的,仅仅因为文件可以链接在一起并不意味着它们可以一起工作。不要将链接器不产生警告这一事实视为您的程序正确的标志。

关于C 语法 : Is the following 'extern volatile const' behavior consistent among C compilers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21874720/

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