Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compile mixed C and C++ code?

I have a C++ class and I would like to include in C code, so I wrote a wrapper:

#ifndef __PMPC_CMPC__
#define __PMPC_CMPC__

#ifdef __cplusplus
extern "C"
#endif
void init_motor();

#ifdef __cplusplus
extern "C"
#endif
double* calc_cont_sig(double  * );

#endif

and this is a simple test

#include "cmpc_ekf.h"
#include <stdio.h>
int main(int argc, char* argv[]) {
    init_motor();
}

I tried to use static library to include the C++ code, so this is my Makefile:

all : main.o libcmpc_ekf.a
    gcc $(EFLAGS) $(CFLAGS) -static  -o main.out main.o  -L. -lcmpc_ekf

main.o: libcmpc_ekf.a
    gcc $(EFLAGS) $(CFLAGS) -static  -c main.c -L. -lcmpc_ekf

libcmpc_ekf.a: cmpc_ekf.o
    ar  rcs libcmpc_ekf.a  cmpc_ekf.o

cmpc_ekf.o: 
    g++ $(EFLAGS) $(CPPFLAGS) -c cmpc_ekf.cpp

clean:
    rm *.o main.out 

But I'm getting the following errors(this is only a token from the error code)

cmpc_ekf.cpp:(.text+0x40): undefined reference to `std::cout'
cmpc_ekf.cpp:(.text+0x45): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'

If I'm using g++ to create the binary file than everything is working. How can I include a C++ class or library into a C code without using g++ or -lstdc++ when I'm creating the binary?

like image 925
OHLÁLÁ Avatar asked Nov 04 '22 08:11

OHLÁLÁ


1 Answers

It is straightforward to include C code in a C++ application (as you discovered when you used g++ to build the binary). However, going the other way isn't really supported. I won't say it is impossible but your "C" code would have to link in the C++ runtime and then initialize the C++ runtime space. Later on, it would have to terminate the C++ runtime as well. I can't think of a reason to do that offhand. Instead, just create the application as C++ and link in the C code whose runtime is a subset of the C++ runtime.

I should clarify that all this means is compiling your C code with the C++ compiler. It takes care of all of the above for you.

like image 138
DrC Avatar answered Nov 08 '22 21:11

DrC