c++ - 两个文件中相同函数/全局变量的不同声明

标签 c++ c function global-variables forward-declaration

在 C 和 C++ 的情况下,我有 2 个关于相同函数和全局变量在两个文件中的不同声明的问题。

  1. 不同的函数声明

    考虑以下代码片段:

    file_1.c

    void foo(int a);
    
    int main(void)
    {
        foo('A');
    }
    

    file_2.c

    #include <stdio.h>
    
    void foo(char a)
    {
        printf("%c", a); //prints 'A' (gcc)
    }
    

    正如我们所见,原型(prototype)不同于位于 file_2.c,但是,该函数打印预期值。

    如果涉及到C++,上面的程序由于undefined而无效 在链接时引用 foo(int)。这可能是由 存在其他函数签名 - 与 C 相比,其中 函数名称不包含任何额外的字符表明 函数参数的类型。

    但是当涉及到 C 时呢?由于具有相同的原型(prototype) 无论参数的数量如何,名称都具有相同的签名 及其类型,链接器不会发出错误。但是哪种类型 转换在这里进行?它看起来像这样吗:'A' -> int -> 返回 char?或者也许这种行为是 未定义/实现定义?

  2. 全局变量的不同声明

    我们有两个文件和相同的两个不同声明 全局变量:

    file_1.c

    #include <stdio.h>
    
    extern int a;
    
    int main(void)
    {
        printf("%d", a); //prints 65 (g++ and gcc)
    }
    

    file_2.c

    char a = 'A';
    

    在 C 和 C++ 中,输出都是 65。

    虽然我想知道这两种标准对那种 情况。

    在 C11 标准中,我发现了以下片段:

    J.5.11 Multiple external definitions (Annex J.5 Common extensions)
    There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).

    请注意,它指的是两个或多个定义的存在,在 我的代码只有一个,所以我不确定这篇文章是否是一个很好的引用点 这种情况...

最佳答案

Q1。根据 C99 规范,第 6.5.2.2.9 节,它是 C 中的未定义行为:

If the function is defined with a type that is not compatible with the type (of the expression) pointed to by the expression that denotes the called function, the behavior is undefined.

表达式“指向”采用 int 的函数,而该函数被定义为采用 char

Q2。变量的情况也是未定义的行为,因为您正在读取或分配一个 int 到/从 char。假设是 4 字节整数,这将访问超过有效内存位置的三个字节。您可以通过声明更多变量来测试它,如下所示:

char a = 'A';
char b = 'B';
char c = 'C';
char d = 'D';

关于c++ - 两个文件中相同函数/全局变量的不同声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12140820/

相关文章:

c++ - 在虚函数、function_pointer 和 functor 之间进行选择

c - 段错误问题,无法检测

c - 如何比较 "text"(字符串)以用作 if 语句的条件

php - 将默认参数作为 null 发送并使用函数中设置的默认值

c++ - Qt metaObject 链接器问题

strncpy 的 C++ 等价物

python - C python 扩展中的段错误

Swift:如何通过引用函数传递对象数组

c - 如何使用 libpq 调用 pg 函数并获取参数值

c++ - 如何为子类 QComboBox 编写 paintEvent()