Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Visual Studio中同时使用.c和.cpp文件 试图找出如何使用C和C++文件编译的应用程序。不是全部代码,但足以让您了解:_C++_C_Visual Studio 2010_Compilation_Compiler Errors - Fatal编程技术网

在Visual Studio中同时使用.c和.cpp文件 试图找出如何使用C和C++文件编译的应用程序。不是全部代码,但足以让您了解:

在Visual Studio中同时使用.c和.cpp文件 试图找出如何使用C和C++文件编译的应用程序。不是全部代码,但足以让您了解:,c++,c,visual-studio-2010,compilation,compiler-errors,C++,C,Visual Studio 2010,Compilation,Compiler Errors,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();

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();
}
#包括
#包括
#包括
#包括“1.h”
#包括“2.h”
int u_stdcallwinmain(HINSTANCE hInst,HINSTANCE hInst2,LPSTR lpCmdLine,int nShowCmd){
函数一();
函数二();
}
1.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() {
}
#包括
#包括
#包括
#包括
#包括
使用名称空间Gdiplus;
使用名称空间Gdiplus::DllExports;
int FunctionOne(){
}
二、c

#包括
#包括
#包括
int FunctionTwo(){
}
头文件仅包含这些函数的定义

现在,如果我用main.cpp编译这个函数,我会得到一个“未解析的外部符号”作为FunctionTwo。如果我用main.c编译这个函数,我会得到与FunctionOne相同的结果。这可能吗?如果可能,我将如何设置项目以正确编译(VisualStudio2010)

如果根据main的扩展名注释掉备用函数,则编译效果良好


谢谢

C++不支持函数重载,而C不支持函数重载。您必须将您的函数标记为
extern“C”
,以防止名称混乱

// main.cpp

extern "C" int FunctionTwo();

.. the rest ..

// two.c

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

<>参见混合C和C++的更多信息。

< P>问题是代码> 2。h < />代码,几乎不允许编写C++编译器正确编译C函数原型。您将希望利用预定义的_ucplusplus宏,如下所示:

二、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"
}
#包括
#包括
#包括
#包括“1.h”
外部“C”{
#包括“2.h”
}

有些程序员命名他们的头文件。HPP如果包含C++声明,如果包含C声明,则为H。这是我个人喜欢的一个很好的做法。推进团队也是如此。它没有使整个世界着火。

参见-> -MSVS编译<代码> .c/>文件作为C和<代码> .CPP < /Cord>文件为C++。为什么不只是<代码>函数2< /C>?代码>功能代码< /COD>编译为C++,不,谢谢您的响应。这被标记为一个副本,但我无法找到另一个答案,因为它没有集中在我的脑海中的问题的措辞(C对C++而不是消息本身)。你的解决方案对我有效。
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "one.h"
extern "C" {
#include "two.h"
}