简体   繁体   中英

Calling C++ functions from a C src

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 (ac -> 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

ac

#include "b.h"

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

bh

#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 : '}'

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++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM