How do I compile "c++ functions from c" if c++ functions need other libraries?

StackOverflow https://stackoverflow.com/questions/23676176

  •  23-07-2023
  •  | 
  •  

Frage

I have these files in the same folder:

function.h
function.cpp
main.c

If I have a simple function like sum(int a){return a+a;} (in function.cpp), I am able to compile it, but I need to use a library like this:

#include "something.hh"
void function(){
   ClassX* test;
   ...
}

The problem is that, when I'm trying to compile this, I get "undefined reference" in every class.

How should I compile this? Is this possible? I've read somewhere you can use a c++ function in c while its return type and its parameters are accessible from C. Is there any other requirement?

What I do:

g++ -c -I /folder/include  function.cpp -o function.o
gcc -c main.c -o main.o
gcc main.o function.o -o exec

In function.cpp undefined reference to ClassX

War es hilfreich?

Lösung

I think your problem is not use of C and C++ but that file containing entire ClassX is not compiled and hence in the third stage in link time it gives error

gcc main.o function.o -o exec

Make sure that ClassX is defined in one .o file and that file is passed in above step.

Now coming to your question, you can't compile C++ code is C compilers because C is not forward compatible but C++ is backward compatible to C that is to say that most of the C code will get compiled by C++ compiler with little change. But you can write a library in c or compile c code to .o and then use it in C++ compiler to do that you need to use extern "C" linkage.

extern "C"
{
....
}

Check this link

Thanks

Andere Tipps

How should i compile this? Is this possible?

Normally, there are two possibilities:

  1. define your header file API in terms of functions only, declare those functions with extern "C" linkage and use them in C code.

  2. if you have class declarations or other C++ specific code, compile your client code to C++ (i.e. move main.c to main.cpp).

In your case, you are trying to access a C++ class, in C code. This is not possible.

You can still use the functionality, but you will have to create an adaptation layer (with APIs declared as extern "C" and declaring no classes, templates or other C++ features).

Within this adaptation layer, classes or other C++ constructs can be hidden in structures opaque to client code.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top