我正在将 C 文件更改为 C++ 文件(最终将其与 C 程序集成)。我是 C++ 的新手,事实上这是我第一次接触它。我有一个声明函数 main 和 hello 的 test.cpp 文件,如下所示:
#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 was not declared in this scope”。
有什么建议吗?
另外,在哪里可以找到 C++ 类及其函数的 API?
最佳答案
我认为您可能误读了错误消息。唯一会导致错误的错误是您没有使用 std::
限定 endl
。您确定错误消息与 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 语言链接。
(请注意,将 extern "C"
添加到函数 hello
的定义中并没有什么坏处——而且可能更清楚,但这不是必需的只要第一个可见声明声明了正确的语言链接。)
关于c++ - Main 无法调用函数 : function was not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22127000/