在C和C++中,"在此范围内未声明变量"

pan*_*ihg 3 c c++ compilation

我今天发现C和C++之间存在差异.我把程序分成两个不同的文件,这是我的C测试:

/* in file main.c*/
#include <stdio.h>

int main()
{
    int a = 3, b = 4;
    int c = sum(a, b);
    printf("%d\n", c);
}
Run Code Online (Sandbox Code Playgroud)

/* In file sum.c */
#include <stdio.h>

int sum(int x, int y)
{
    return x + y;
}
Run Code Online (Sandbox Code Playgroud)

然后,我编译它们gcc main.c sum.c,没有错误,结果是正确的.以下是我的C++测试,我还将它们分成两个不同的文件:

/* in file main.cpp*/
#include <iostream>

int main()
{
    int a = 3, b = 4;
    int c = sum(a, b);
    std::cout << c << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

/* In file sum.cpp */
#include <iostream>

int sum(int x, int y)
{
    return x + y;
}
Run Code Online (Sandbox Code Playgroud)

编译它们g++ main.cpp sum.cpp.发生错误:error: ‘sum’ was not declared in this scope.如果我int sum(int, int)在文件中放入声明main.cpp,则不会发生错误.为什么C和C++之间存在这样的差异?什么是解决它的最佳方法?

Ton*_*roy 7

它是C++引入的一个特性:除非你真的看过声明或定义,否则不要假设你知道函数签名.在编译器和链接过程中更容易报告不正确的函数使用,并且使用C++名称修改,需要确切的参数类型来知道代码需要链接的符号 - 类型确定基于与候选者的匹配,可以进行各种标准转换/隐式构造/隐式转换.

解决此问题的正确方法是创建sum.h头文件:

#ifndef SUM_H
#define SUM_H
int sum(int, int);
#endif
Run Code Online (Sandbox Code Playgroud)

这应该包含在第一行或sum.cpp(因此,如果sum.h内容演变为依赖于<iostream>内容但是忘记将其自身包含在内,则会出现错误),并且在main.cpp其他内容之前或之后包含您喜欢的内容(我会危害大多数人)会放在后面,但这是一个风格选择).