Integrate C and C ++

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 this? I researched and saw that "extern" can help but I am 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 I made it hard to read.

    
asked by anonymous 07.06.2016 / 16:13

1 answer

1

You can not compile a C ++ code in C , but you can compile a 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;
}

Compilation is required 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 C ++ functionalities.

The most viable way to do this is to use 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 divides your code by leaving one part in C and C ++ .

  

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

    
08.06.2016 / 00:41