Main 不能调用函数:函数未在此范围内声明

Main can not call a function: function was not declared in this scope

本文关键字:函数 范围内 声明 不能 调用 Main      更新时间:2023-10-16

我正在将C文件更改为C++文件(最终将其与C程序集成)。我对C++很陌生,事实上这是我第一次接触它。我有一个 test.cpp 文件,它声明函数 main 和你好,如下所示:

#include "test.h"
int main()
{
    hello ();
    return 0;
}
void hello()
{
    std::cout << "Hello there!" << endl;
}

test.h 文件声明如下:

#include <iostream>
extern "C" void hello();

当我使用 g++ test.cpp 编译程序时,出现错误"hello 未在此范围内声明"。

有什么建议吗?

另外,在哪里可以找到C++类及其函数的 API?

我认为

您可能误读了错误消息。应该导致错误的唯一错误是您没有endl符合std::资格。您确定错误消息与endl无关吗?

编译您的完整测试用例,我得到以下内容:

$ g++ test.cpp
test.cpp: In function ‘void hello()’:
test.cpp:11:37: error: ‘endl’ was not declared in this scope
      std::cout << "Hello there!" << endl;
                                     ^
test.cpp:11:37: note: suggested alternative:
In file included from /usr/include/c++/4.8/iostream:39:0,
                 from test.h:1,
                 from test.cpp:1:
/usr/include/c++/4.8/ostream:564:5: note:   ‘std::endl’
     endl(basic_ostream<_CharT, _Traits>& __os)
     ^

通过将std::添加到endl来修复错误可修复所有编译和链接错误hello并按预期提供 C 语言链接。

(注意,在函数hello的定义中添加extern "C"没有害处 - 而且可能更清楚,但只要第一个可见声明声明了正确的语言链接,就没有必要。

问题是你在包含文件中extern "C"声明它,但它在 hello.cpp 源文件中,所以它将被编译为 c++,而不是 c。

你应该完全删除extern "C"
使用标准命名空间。

但是,如果您必须将函数编译为 extern "C" ,则不需要将其放在函数定义之前,只需将声明放在您已经完成的声明之前。
但是,如果您想将其添加到声明和定义中,则可以这样做。

例:

#include "test.h"
using namespace std;    
int main()
{
    hello ();
    return 0;
}
void hello()
{
    cout << "Hello there!" << endl;
}