gpt4 book ai didi

c - 为什么我在 C 中得不到枚举的 'Multiple Definitions'?

转载 作者:太空狗 更新时间:2023-10-29 17:02:58 24 4
gpt4 key购买 nike

假设我有三个文件:

//m.h
const int RED = 1;
//m.h ends here

//f1.c
#include "m.h"
//f1.c ends here


//f2.c
#include "m.h"
int main() {return 0;}
//f2.c ends here

单独编译每一个都可以,但是 gcc -Wall f1.o f2.o -o prog将产生: multiple definition of 'RED'

现在,如果我将 const 替换为:

//m.h
enum {RED=1} colors;
//m.h ends here

我将能够编译 prog并使用 RED作为常量,不会得到任何 multiple definition错误。

为什么 enum 的行为当您在不同的文件中具有同名的全局变量或结构时,它与可见的不同吗?

最佳答案

枚举不会在内存中创建值,这意味着链接时没有地址添加到符号表。

const 变量将在编译对象中有一个地址,带有一个符号名。当您尝试将两个目标文件链接在一起时,它们每个都有指向不同地址的相同符号名称“RED”,这就是导致冲突的原因。

关于c - 为什么我在 C 中得不到枚举的 'Multiple Definitions'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390246/

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