【发布时间】:2014-04-03 08:01:48
【问题描述】:
我正在将 C 文件更改为 C++ 文件(最终将其与 C 程序集成)。我对 C++ 非常陌生,事实上这是我第一次接触它。我有一个 test.cpp 文件,它声明函数 main 和 hello 如下:
#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 is not declared in this scope”。
有什么建议吗?
另外,在哪里可以找到 C++ 类及其函数的 API?
【问题讨论】:
-
你发出的命令是什么?
-
所以如果一个 C 程序,比如 myprog.c,需要调用函数 hello(),我会在 myprog.h 中将该函数声明为 extern "C" void hello?
-
从 C 调用 C++ 很难,至少比从 C++ 调用 C 更难。最好将不需要 c++ 的所有函数放在单独的
.c源文件中,以便将它们编译为 C,并从 C++ 源文件中声明它们为 extern "C"。在 .h 文件中的“extern C”周围放置一些#ifdef __CPLUSPLUS,这样您就可以从两种语言中包含它们;检查标准包含文件以获取示例。 -
感谢您提供完整的可编译测试用例,但能否请您发布您遇到的实际错误的全文?
-
-1 您问题中的代码与错误信息不符