top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can we call C function from C++

+5 votes
349 views
How can we call C function from C++
posted Jan 18, 2014 by Neeraj Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+3 votes

Compile the C code like this:
gcc -c -o somecode.o somecode.c

Then the C++ code like this:
g++ -c -o othercode.o othercode.cpp

Then link them together, with the C++ linker:
g++ -o yourprogram somecode.o othercode.o

You also have to tell the C++ compiler a C header is coming when you include the declaration for the C function. So othercode.cpp begins with:

extern "C" {
#include "somecode.h"
}

somecode.h should contain something like:

#ifndef SOMECODE_H_
 #define SOMECODE_H_

 void foo();

 #endif
answer Jan 19, 2014 by Atul Mishra
There is a __cplusplus if you are in C++ environment and can use of this macro something like which will make your code completely portable -

#ifdef __cplusplus
extern "C" {
#endif

void foo();

#ifdef __cplusplus
}
#endif
Similar Questions
0 votes

http://perldoc.perl.org/perlembed.html

Above link only shows calling from C to perl.

What I want to do is to create a function in C code and somehow export it to my embedded perl interpreter. Then I want to be able to call this C function from perl code.

Can someone point me to a good example on how to do this?

+6 votes
...