【问题标题】:Using .c and .cpp files in Visual Studio at the same time同时在 Visual Studio 中使用 .c 和 .cpp 文件
【发布时间】:2012-09-27 21:24:05
【问题描述】:

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

main.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() {
}

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

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

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

谢谢!

【问题讨论】:

标签: c++ c visual-studio-2010 compilation compiler-errors


【解决方案1】:

问题是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团队也是如此。否则它并没有让世界着火。

【讨论】:

  • 感谢您的回复。这被标记为重复,但我无法找到另一个答案,因为它没有关注我脑海中问题的措辞(C 与 C++ 而不是消息本身)。你的解决方案对我有用。
【解决方案2】:

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

【讨论】:

  • 为什么不只是FunctionTwoFunctionOne 被编译为 C++,不是吗?
猜你喜欢
  • 2021-12-19
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2015-02-03
  • 2015-07-11
相关资源
最近更新 更多