Mixed project c and c++ -> possible?

stefanoxjx
Posts: 25
Joined: Mon Feb 12, 2018 6:26 pm

Mixed project c and c++ -> possible?

Postby stefanoxjx » Sat Mar 17, 2018 9:08 am

Hi,
I've a library in cpp and some libs in c.
Exist a way to compile a mixed project?
I tried to rename the C files in cpp, but I'm submerged from errors.
For me, convert the cpp libs in C is very difficult, but convert C files in cpp is even more difficult.
The interested libs are espmqtt (writed in C) and this https://github.com/imxieyi/esp32-i2c-mpu6050 (writed in C++),

Thanks.

Stefano

User avatar
kolban
Posts: 1683
Joined: Mon Nov 16, 2015 4:43 pm
Location: Texas, USA

Re: Mixed project c and c++ -> possible?

Postby kolban » Sat Mar 17, 2018 4:04 pm

To the best of my knowledge, you can freely mix C and C++ object files. A common problem is to realize that if you have a source file called a.cpp which define

Code: Select all

void aFunc() {
}
You can't simply call it from a source file called b.c as:

Code: Select all

extern void aFunc() {
}

void bFunc() {
   aFunc();
}
Instead, you will have to define aFunc() as a C function with the following in a.cpp

Code: Select all

extern "C" void aFunc() {
}
Free book on ESP32 available here: https://leanpub.com/kolban-ESP32

User avatar
fly135
Posts: 606
Joined: Wed Jan 03, 2018 8:33 pm
Location: Orlando, FL

Re: Mixed project c and c++ -> possible?

Postby fly135 » Sat Mar 17, 2018 4:13 pm

Depends... If you want to call C code from C++, then no problem. Simply surround the C dot H includes with....

extern "C"
{
#include "myC.h"
#include "myotherC.h"
}


The other way around isn't practical. But if I say it can't be done then someone will come in and show how to do it. The exported names of C++ functions aren't the same as they appear. They are "mangled". Also C++ functions have the hidden "this" parameter. All of this makes calling C++ from C a problem.

John

Who is online

Users browsing this forum: No registered users and 110 guests