c++ - Main 无法调用函数 : function was not declared in this scope

标签 c++ c

我正在将 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/

相关文章:

c++ - 将哈希值存储到 int

c++ - 实现低优先级后台线程的模式?

c++ - 为什么我的 switch 语句没有响应一半的情况?

c - 处理函数中的偏移量

c - 将位从一个字节移到一个(数组)

c++ - 一旦到达主函数末尾,就会发生调试运行时堆栈错误

c++ - 在 C++ 中匹配俄语元音

c - 合并的链表

C 学生作业,数组值未传递给函数

无法执行 if 处的命令