本文介绍了理解 C 命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用这里

在 C 中,有两种不同的类型命名空间:结构/联合/枚举标记名称的命名空间和 typedef 名称的命名空间.

name.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 命名空间冲突.

I am trying to understand C namespace conflicts.

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

  • In the first case, why is there a conflict? Do functions also belong to the typedef namespace?

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

In the second case, why is there no conflict at all? The function and the variable both are named four. Why does the compiler allow that? How is &four supposed to be resolved?

推荐答案

C 有四种不同的标识符命名空间:

C has four different name spaces for identifiers:

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

另见 C99 6.2.3.

See also C99 6.2.3.

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

So your two question can be answered as:

  1. 是的,函数名和 typedef 名共享同一个命名空间.
  2. 没有冲突,因为编译器将使用范围规则(用于函数或对象名称).main 中的标识符被称为 shadow 全局函数名,如果您将警告级别设置得足够高,您的编译器会警告您.
  1. Yes, function names and typedef names share the same name space.
  2. No conflict, because the compiler will use scope rules (for function or object names). The identifier in main is said to shadow the global function name, something your compiler will warn you about if you set the warning levels high enough.

这篇关于理解 C 命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 01:21