Main 不能调用函数:函数未在此范围内声明
Main can not call a function: function was not declared in this scope
我正在将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;
}
相关文章:
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 哪个函数负责C++全局范围内的类对象初始化?
- 如何将不在 QT 全局范围内的函数附加到 Qwidget 上
- 在命名成员函数重载解析期间,"this"何时不在范围内?
- GCC 或 Clang 关于函数参数在其自己的默认参数中的范围内的名称是否正确?
- 函数未在此范围内声明
- 模板化函数范围内的条件模板化类型别名
- 在某个值范围内生成 BST 的泛型函数
- 在构造函数中 'cout' 未在此范围内声明
- 通过使用全局变量的函数访问在给定范围内被覆盖的变量
- 是否有函数可以检索范围内可用非重复值的数量
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- C++ 收到错误,指出函数未在此范围内声明
- 是否可以编写一个在函数范围内使用时会抱怨的宏
- Arduino-setup()中声明的变量不在函数范围内
- C++-函数范围内的函数声明
- 我是否要删除函数范围内的内存?
- ISO C++03对在函数范围内定义的结构有什么限制
- OpenGL中绘制函数范围内的静态变量