top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How can I create a C++ function f(int,char,float) that is callable by my C code?

+10 votes
474 views
How can I create a C++ function f(int,char,float) that is callable by my C code?
posted Apr 27, 2016 by Shivam Kumar Pandey

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

2 Answers

0 votes

The C++ compiler must know that f(int,char,float) is to be called by a C compiler using the extern "C" construct:

// This is C++ code

// Declare f(int,char,float) using extern "C":
extern "C" void f(int i, char c, float x);

...

// Define f(int,char,float) in some C++ module:
void f(int i, char c, float x)
{
...
}
The extern "C" line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling (e.g., preceded by a single underscore). Since name overloading isn't supported by C, you can't make several overloaded functions simultaneously callable by a C program.
reference-http://www.cs.technion.ac.il/users/yechiel/c++-faq/c-calls-cpp.html

answer Apr 27, 2016 by Devendra Bohre
0 votes

Not sure whether its the best way to do it but generally i prefer this way,
Create a ".cpp" file say test.cpp, compile it with -C option and generate an '.o' file
Then, create one .c file declare and Call that cpp function from here, and compile it with g++

Below is the example,

**

test.cpp

**

#include<iostream>
using namespace std;
int sum(int a,int b)
{
        return a+b;
}

**

test2.c

**

#include<stdio.h>
int sum(int,int);
main()
{
        printf("sum = %d\n",sum(10,20));
}

**

Do below stepst to compile and run

**,

g++ -C test.cpp -o test.o
g++ test2.c test.o 
answer Apr 28, 2016 by Chirag Gangdev
Similar Questions
+1 vote

What type of conversion is not accepted in C and why?
a) char to int
b) float to char pointer
c) int to char
d) double to char

+6 votes
+4 votes

I am wanting to extract variable names and their size (int, char and etc.) from a c file.
Is there any way to extract that type of information?

...