Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .c and .cpp files in Visual Studio at the same time

Trying to figure out how to get an application to compile that uses both C and C++ files. Not the entire code, but enough to get the idea:

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();
}

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

two.c

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

int FunctionTwo() {
}

The header files contain only definitions for those functions.

Now, if I compile this with a main.cpp, I get an "unresolved external symbol" for FunctionTwo. If I compile this with a main.c, I get the same thing for FunctionOne. Is this even possible, and if so, how would I set up the project to compile properly (Visual Studio 2010)?

It compiles fine if I comment out the alternate function depending on the extension for main.

Thanks!

like image 1000
Fmstrat Avatar asked Oct 16 '25 03:10

Fmstrat


1 Answers

The problem is two.h, it almost certainly wasn't written to allow a C++ compiler to properly compile the C function prototype. You'll want to take advantage of the predefined __cplusplus macro, like this:

two.h:

#ifdef __cplusplus
extern "C" {
#endif

int FunctionTwo();
// etc...

#ifdef __cplusplus
}
#endif

Lovely macro soup ;) If the header is pre-baked and never saw a C++ compiler before then do this in your .cpp source code file:

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

Some programmers name their header files .hpp if they contain C++ declarations and .h if they contain C declarations. That's a pretty good practice I personally favor. So does the Boost team. It didn't otherwise set the world on fire.

like image 115
Hans Passant Avatar answered Oct 17 '25 17:10

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!