2

I have mixed code base of C/C++ in a MS Visual Studio 2010 project and am trying to call a static function defined in C++ file from a C src file. Right now I get it to work by renaming the C src to CPP (a.c -> a.cpp) Just wondering if there's a more graceful way of getting around it (turning some magic compiler flags on etc) without doing any large scale surgery to the code base(like using opaque pointers as suggested in this thread)

Pls note my code base is pretty complex, I have created this small VS snippet to reproduce the error with bare minimum demonstrable code

a.c

#include "b.h"

void test()
{
  B::func();
}

b.h

#ifdef __cplusplus
extern "C" {
#endif

class B{
public:
  static void func();
};

#ifdef __cplusplus
}
#endif

b.cpp

#include "b.h"

#ifdef __cplusplus
extern "C" {
#endif

void B::func()
{
  return;
}

#ifdef __cplusplus
}
#endif

Error:- In MS Visual Studio 2010

1>c:\.....\b.h(5): error C2061: syntax error : identifier 'B'
1>c:\.....\b.h(5): error C2059: syntax error : ';'
1>c:\.....\b.h(5): error C2449: found '{' at file scope (missing function header?)
1>c:\.....\b.h(8): error C2059: syntax error : '}'
Zakir
  • 2,222
  • 21
  • 31
  • It's not exactly a pretty solution, but you can also force VC to compile the file as CPP without renaming it. The command line flag is `/TP`. – kichik May 30 '17 at 23:55

1 Answers1

5

First, :: is not valid in C.

Second, including a header is equivalent to copy-pasting a .h file into your C file. Your header must be valid C. Here's some deeper insight:

How to call C++ function from C?

Elegantly call C++ from C

Though, my alternative advice is, compile your C as C++. There's a chance it would take minimal or no work to turn out as valid C++.

Sam Pagenkopf
  • 258
  • 1
  • 5
  • I am trying to avoid wrapping around C++ methods – Zakir May 31 '17 at 00:17
  • 1
    @Zakir Why are you keen to avoid wrappers? If it's to avoid repeating code, then you can use tools like T4 with EnvDTE (both built-in to Visual Studio) to automatically generate a `.h` file for C based on your C++ code, and also use it to automatically generate a wrapper too. – Dai May 31 '17 at 01:05
  • @Dai - I will play around with the tools Tnx! – Zakir May 31 '17 at 01:36