Integrate C and C++

Asked

Viewed 234 times

2

Good morning, everyone.

I have a main program in C, and I just want to call a function that is in another C++ file and get the return of this function.

How do I do that? I researched and saw that "extern" can help but I’m not succeeding.

Here’s what I want to do: In the program. c:

#include <stdio.h> 
#include <stdlib.h> 
#include "chain_code.cpp" // Arquivo C++ 
extern int chains(char*); 

int main (int argc, char* argv[]){ 

      // Faz alguma coisa 

     printf("%d ", chains(argv[1])); // Chama a função que está programada em C++

}

In the file "chaincode.cpp":

#include "opencv2/core/core.hpp" 
#include "opencv2/imgproc/imgproc.hpp" 
// Outros includes 


int chains(char* path){ 

// Gera histograma da imagem Path 
// devolve a media do histograma 

I’m new here so I’m sorry if I made reading a little difficult

  • 1

    It is not advisable to call C++ code from C. The C++ compiler does "name mangling" which makes the functions hidden to C. C++ has exceptions in its internal library and the C compiler does not know how to handle it, It is easier to use C based on C++.

  • Hmm.. And how would I do that?

  • 3

    "and how would I do that?" Writes the main program in C++. All language mixing problems cease to exist :-)

  • If your routine is not a class, simply put the statement exactly as it is written. The Font should be in the project and not as a include. The compiler is in charge of locating the routine.

  • It happens to have other functions already developed in C, and this will not be possible

1 answer

1

Cannot compile a code C++ in C, but it is possible to compile a code C in C++.

main. c:

#include <stdio.h>

extern int sum(int x, int y);

int main(int argc, char **argv){
    printf("O código da: %d\n", sum(15,5));

    return 0;
}

sum.cpp:

#include <iostream>

using namespace std;

extern "C" int sum(int x, int y){
    cout << (x+y) << endl;
    return x+y;
}

It is necessary to compile in parts.

gcc main.c -o main.o -c
g++ sum.cpp -o sum.so -c
g++ main.o sum.o -o programa.exe

With this, everything is integrated into the functionalities of C++.

The most viable way to do this is by using dynamic libraries.

g++ -fPIC -shared sum.cpp -o sum.so # sum.dll caso esteja no windows
gcc main.c ./sum.so # sum.dll caso esteja no windows

This method splits your code leaving a part in C and another in C++.

Note: If you are going to integrate C with C++, do all your work in C+, this is something not worth mixing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.