gpt4 book ai didi

c - 理解 C 命名空间

转载 作者:太空狗 更新时间:2023-10-29 16:25:10 26 4
gpt4 key购买 nike

引自here ,

In C, there are two different namespaces of types: a namespace of struct/union/enum tag names and a namespace of typedef names.

名称.c

$ cat name.c
#include<stdio.h>

typedef long long long2;

int long2 () {
return 4;
}

int main() {

printf("hello, world!");
return 0;
}
$ gcc name.c -o name
name.c:4: error: 'long2' redeclared as different kind of symbol
name.c:3: error: previous declaration of 'long2' was here
$

name2.c

$ cat name2.c
#include<stdio.h>

int four() {
return 4;
}

struct dummy {
int member;
};

int main() {

struct dummy four;
}

$ gcc name2.c -o name2
$

我正在尝试了解 C namespace 冲突。

  • 第一种情况,为什么会有冲突?函数是否也属于 typedef 命名空间?

  • 第二种情况,为什么完全没有冲突呢?函数和变量都命名为四。为什么编译器允许这样做? &four应该怎么解决?

最佳答案

C 有四种不同的标识符 namespace :

  • 标签名称(goto 类型)。
  • 标签(结构、 union 和枚举的名称)。
  • 结构和 union 的成员(每个结构/union 有一个单独的命名空间)。
  • 所有其他标识符(函数名称、对象名称、类型(def)名称、枚举常量等)。

另请参阅 C99 6.2.3。

所以你的两个问题可以这样回答:

  1. 是的,函数名称和 typedef 名称共享相同的 namespace 。
  2. 没有冲突,因为编译器将使用范围规则(用于函数或对象名称)。据说 main 中的标识符隐藏全局函数名称,如果您将警告级别设置得足够高,您的编译器会警告您。

关于c - 理解 C 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3793952/

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