Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling C++ functions from C file

Tags:

c++

c

merge

call

I am quite new to C and C++. But I have some C++ functions which I need to call them from C. I made an example of what I need to do


main.c:

#include "example.h"      
#include <stdio.h>

int main(){   
    helloWorld();
    return 0;
}

example.h:

 #ifndef HEADER_FILE
 #define HEADER_FILE

 #ifdef __cplusplus
     extern "C" {
 #endif
         void helloWorld();
 #ifdef __cplusplus
     }
 #endif

 #endif

example.cpp:

#include <iostream.h>

void helloWorld(){
    printf("hello from CPP");
} 

It just doesn't work. I still receive the error of undefined reference to _helloWorld in my main.c. Where is the the problem?

like image 478
user1702375 Avatar asked Sep 27 '12 06:09

user1702375


People also ask

How do you call a function from another file in main C?

You must declare int add(int a, int b); (note to the semicolon) in a header file and include the file into both files. Including it into Main. c will tell compiler how the function should be called.

Can we call C function from C++?

If you declare a C++ function to have C linkage, it can be called from a function compiled by the C compiler. A function declared to have C linkage can use all the features of C++, but its parameters and return type must be accessible from C if you want to call it from C code.

Can you include .C files?

You can properly include . C or . CPP files into other source files.


1 Answers

Short answer:

example.cpp should include example.h.

Longer answer:

When you declare a function in C++, it has C++ linkage and calling conventions. (In practice the most important feature of this is name mangling - the process by which a C++ compiler alters the name of a symbol so that you can have functions with the same name that vary in parameter types.) extern "C" (present in your header file) is your way around it - it specifies that this is a C function, callable from C code, eg. not mangled.

You have extern "C" in your header file, which is a good start, but your C++ file is not including it and does not have extern "C" in the declaration, so it doesn't know to compile it as a C function.

like image 100
asveikau Avatar answered Sep 27 '22 22:09

asveikau