Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing C functions in static library from C++

I have a static library of functions written in C. Let's say the header file is called myHeader.h and looks like:

#ifndef MYHEADER_H
#define MYHEADER_H

void function1();
void function2();

#endif

function1 and function2 aren't anything too special. Let's say they exist in a file called impl1.c which looks like:

#include "myHeader.h"

void function1() {
    // code
}
void function2() {
    // more code
}

All of the code mentioned so far is compiled into some static library called libMyLib.a. I'd rather not modify any of the code used to build this library. I also have a C++ header (cppHeader.h) that looks like:

#ifndef CPPHEADER_H
#define CPPHEADER_H

class CppClass {
    private:
        double attr1;
    public:
        void function3();
};
#endif

Then cppHeader.cpp looks like:

#include "cppHeader.h"
#include "myHeader.h"

// constructor
CppClass::CppClass(){}

void CppClass::function3() {
    function1();
}

When I try to compile this, I get an error about an undefined reference to function1(). I believe that I've linked everything properly when compiling. I'm pretty rusty in my C++. I'm sure that I'm just doing something stupid. I hope that my simple example code illustrates the problem well enough.

Thanks in advance for any help!

like image 507
Ryan Avatar asked Dec 29 '22 00:12

Ryan


1 Answers

The other solution (to the one suggested originally by Yann) is to surround your "C" header with:

 #ifdef __cplusplus
 extern "C" {
 #endif

 #ifdef __cplusplus
 }
 #endif 

Which saves you from having to remember to do:

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

every place you use foo.h

like image 73
Flexo Avatar answered Jan 11 '23 00:01

Flexo