3

试图弄清楚如何让使用 C 和 C++ 文件的应用程序进行编译。不是整个代码,但足以理解:

主.cpp:

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "one.h"
#include "two.h"

int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hInst2, LPSTR lpCmdLine, int nShowCmd) {
    FunctionOne();
    FunctionTwo();
}

一个.cpp:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <gdiplus.h>
#include <gdiplusflat.h>
using namespace Gdiplus;
using namespace Gdiplus::DllExports;

int FunctionOne() {
}

二.c

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int FunctionTwo() {
}

头文件仅包含这些函数的定义。

现在,如果我用main.cpp编译它,我会得到 FunctionTwo 的“未解析的外部符号”。如果我用main.c编译它,我会为 FunctionOne 得到同样的结果。这甚至可能吗?如果可以,我将如何设置项目以正确编译(Visual Studio 2010)?

如果我根据 main 的扩展名注释掉备用函数,它编译得很好。

谢谢!

4

2 回答 2

10

问题是two.h,几乎可以肯定它不是为了让 C++ 编译器正确编译 C 函数原型而编写的。您需要利用预定义的 __cplusplus 宏,如下所示:

二.h:

#ifdef __cplusplus
extern "C" {
#endif

int FunctionTwo();
// etc...

#ifdef __cplusplus
}
#endif

可爱的宏汤;)如果头文件是预烘焙的并且之前从未见过 C++ 编译器,那么在您的 .cpp 源代码文件中执行此操作:

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "one.h"
extern "C" {
#include "two.h"
}

如果头文件包含 C++ 声明,一些程序员将其命名为 .hpp,如果它们包含 C 声明,则将其命名为 .h。这是我个人喜欢的一个很好的做法。Boost团队也是如此。否则,它并没有让世界着火。

于 2012-09-27T21:30:42.053 回答
0

C++ 进行名称修改以支持函数重载,而 C 不这样做。您必须标记您的功能extern "C"以防止名称损坏。

// main.cpp

extern "C" int FunctionTwo();

.. the rest ..

// two.c

extern "C" int FunctionTwo() {
    // stuff
}

有关混合 C 和 C++ 的更多信息,请参阅http://www.parashift.com/c++-faq/mixing-c-and-cpp.html

于 2012-09-27T21:25:44.477 回答