在C ++中引用静态库中的C函数 [英] Referencing C functions in static library from C++

查看:520
本文介绍了在C ++中引用静态库中的C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以C语言编写的函数的静态库。假设头文件名为myHeader.h,如下所示:

  #ifndef MYHEADER_H 
#define MYHEADER_H

void function1();
void function2();

#endif

function1和function2不是太特别。假设它们存在于一个名为impl1.c的文件中,它类似于:

  #includemyHeader.h

void function1(){
// code
}
void function2(){
//更多代码
}

到目前为止提到的所有代码都被编译成一些名为libMyLib.a的静态库。我宁愿不修改任何用于构建此库的代码。我也有一个C ++头(cppHeader.h),看起来像:

  #ifndef CPPHEADER_H 
#define CPPHEADER_H

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

然后cppHeader.cpp看起来像:

  #includecppHeader.h
#includemyHeader.h

// constructor
CppClass :: CppClass(){}

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

当我尝试编译这个时,我得到一个关于未定义的引用的错误function1()。我相信我在编译时正确链接了一切。我在我的C ++相当生锈。我相信我只是做一些蠢事。



< >解决方案

另一个解决方案(Yann最初建议的解决方案)是用C标头包围:

  #ifdef __cplusplus 
externC{
#endif

#ifdef __cplusplus
}
#endif

这样可以避免您不必记住:

  externC{
#includefoo.h
}

您使用的每个地方 foo.h


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!

解决方案

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

这篇关于在C ++中引用静态库中的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆