About Blog Contact

Using C libraries in C++

I have the following C code:

// filename: c_lib.c 
#include <stdio.h>
int c_func() {
    printf("this is c_func");
    return 0;
}

I have compiled it into a static library:

$ gcc -c c_lib.c -o c_lib.o
$ ar rcs libc_lib.a  c_lib.o

I am trying to use it in a C++ program:

//filename : cpp_prog.cpp
#include<iostream>
extern int c_func();
int cpp_func() {
    std::cout << "this is cpp_func" << std::endl;
    c_func();
    return 1;
}
int main() {
   cpp_func();
   return 0;
}

There is a linking error:

$ g++ cpp_prog.cpp -L. -lc_lib -o test
/usr/bin/ld: /tmp/cclWQbqf.o: in function `cpp_func()':
link1.cpp:(.text+0x31): undefined reference to `c_func()'
collect2: error: ld returned 1 exit status

Why? because of name mangling! The symbol generated by the C compiler is not understood by g++! You have to explictly inform g++ that the function you are linking to is using the C convention: that is, the symbol stored in the elf file is the function name, instead of a mangled version that includes its arguments’ types. So you have to write it as:

//filename : cpp_prog.cpp
#include<iostream>
extern "C" {
  extern int c_func();
}
int cpp_func() {
    std::cout << "this is cpp_func" << std::endl;
    c_func();
    return 1;
}
int main() {
   cpp_func();
   return 0;
}