Calling C from C++.

Hey guys,

I'm working on a project where I need to combine both languages; I've never done "real" C. In short, there is one module in C that performs a single, complex calculation. The end result is that there is one function in C that needs to be called from outside; all the rest are support functions for that one function. The entire C "module" can be treated as a black box. It is generated from an outside program and I'd like to minimize the amount of alteration to it because it's possible we end up regenerating the code in future versions. The function takes some ints and returns an int; nothing fancy.

The "main" was inside the .c file where the function was declared and defined and thus directly accessible. I've moved the main function to a new .cpp file and added a .h file where all the functions in the .c file are declared.

[code]#include "CModule.h"

int main()
{
double value = CallCFunction(<some ints>);
printf("%f", value);
return 0;
}

This gives me a linking error:

1>Main.obj : error LNK2019: unresolved external symbol "double __cdecl <name of function with extra nonsense at end> : fatal error LNK1120: 1 unresolved externals
1>

How do I do this correctly? In the future, the CallCFunction will appear in a lot of places in code I wish to write in C++.
Put your include in an extern "C" { } block. This is for name resolution.
Thanks coder777!

I ended up just putting extern "C" in front of the declaration of CallCFunction inside the include, but I imagine the effect is the same.
but I imagine the effect is the same.
This may cause a problems with a c-compiler because it's a C++ directive.
The usual solution for that is
1
2
3
4
5
6
7
#ifdef __cplusplus
#define EXTERN_C extern "C"
#else
#define EXTERN_C
#endif

EXTERN_C void foo();
Topic archived. No new replies allowed.