C ++中缺少前向声明的问题 [英] Issue with missing forward declaration in C++

查看:149
本文介绍了C ++中缺少前向声明的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编译了以下程序,而在C中没有前向声明功能.它已成功编译并在GCC中运行,没有任何警告或错误.

#include <stdio.h>

int main()
{
        int ret = func(10, 5);
}

int func(int i, int j)
{
        return (i+j);
}

但是,我在C++中编译了没有前向声明功能的以下程序,编译器给我一个错误.

#include <iostream>
using namespace std;

int main()
{
        int ret = func(10, 5);
}

int func(int i, int j)
{
        return (i+j);
}

错误:

fl.cpp:6:22: error: ‘func’ was not declared in this scope
  int ret = func(10, 5);
                      ^

为什么C ++编译器会给出错误?默认情况下不是采用int数据类型吗?

解决方案

好吧,C语言中的错误与C ++中一样多.

考虑该问题是基于 假设" ,从C编译器的角度来看,该代码是有效的,让我根据规范进行详细说明( C11),不允许隐式声明函数.严格遵守标准来编译代码,并且(任何符合标准的)编译器会在C语言中产生相同的错误.

查看实时示例

引用C11,前言/p7,第二版中的主要更改包括:"

  • 删除隐式函数声明

C99中也一样.


注意:为什么会起作用

Pre C99,实际上有空间可以成功编译此代码.如果缺少函数原型,则假定函数返回int并接受任意数量的参数作为输入.现在这已经是非常不标准的了,具有旧有支持的编译器可能会选择允许此类代码进行编译,但严格来说,一个合格的编译器应该拒绝这样做.

I have compiled following program without forward declaring function in C. It's successfully compiled and run in GCC without any warning or error.

#include <stdio.h>

int main()
{
        int ret = func(10, 5);
}

int func(int i, int j)
{
        return (i+j);
}

But, I have compiled following program without forward declaring function in C++, Compiler gives me an error.

#include <iostream>
using namespace std;

int main()
{
        int ret = func(10, 5);
}

int func(int i, int j)
{
        return (i+j);
}

An Error:

fl.cpp:6:22: error: ‘func’ was not declared in this scope
  int ret = func(10, 5);
                      ^

Why C++ Compiler Gives an Error? Is it not by default take int data type?

解决方案

Well, it is as much as wrong in C, as in C++.

Considering the question is based on the "assumption" that the code is valid from a C compiler point of view, let me elaborate that, as per the spec (C11), implicit declaration of functions is not allowed. Compile your code with strict conformance and (any conforming) compiler will produce the same error in C.

See live example

Quoting C11, Foreword/p7, "Major changes in the second edition included:"

  • remove implicit function declaration

and the same exist in the C99, also.


Note: On why it might have worked

Pre C99, there was actually room for this code to be compiled successfully. In case of a missing function prototype, it was assumed that the function returns an int and accepts any number of parameters as input. That is now very much non-standard and compilers with legacy support may choose to allow such code to be compiled, but strictly speaking, a conforming compiler should refuse to do so.

这篇关于C ++中缺少前向声明的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆