如何避免C ++中两个库的变量/函数冲突 [英] How to avoid variable/function conflicts from two libraries in C++

查看:78
本文介绍了如何避免C ++中两个库的变量/函数冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的情况,如下所述:

I have similar scenario as explained below:

我有一个头文件 first.h 它具有功能:

I have one header file first.h It has a function :

char* getName();

和具有功能定义的关联cpp文件 first.cpp

and associated cpp file first.cpp having function definition

char* getName(){return "first";}

和第二个头文件second.h它具有以下功能:

and the second header file second.h it has the function:

char* getName();

具有功能定义的关联cpp文件 second.cpp

associated cpp file second.cpp having function definition

char* getName(){return "second";}

现在有一个 main()函数:

#include "first.h"
#include "second.h"

int main(){
return 0;
}

当我包含这些 .h 文件时,编译器会在函数 getName()处给出错误,因为它有冲突.

when I include those .h files, compiler give an error at the function getName() as it is conflicting.

如何在不更改 .h文件

推荐答案

在包含那些头文件时可以使用名称空间:

You can use namespaces when including those header files:

在您的cpp文件中:

namespace first
{
    #include "first.h"
}

namespace second
{
    #include "second.h"
}

然后您可以使用以下功能:

Then you can use the functions as the following:

...
first::getName();
second::getName();
...

编辑:感谢Jens的评论,这仅在函数为内联时有效.如果这些函数不是内联函数,并且您确实无法更改头文件,则可以为这些函数创建包装器"头文件:

Thanks to Jens' comment this only works if the functions are inline. If the functions are not inline and you really can't change the header files you can create "wrapper" header files for those functions:

wrapper-first.h:

File wrapper-first.h:

namespace first
{
    char* getName();
}

wrapper-first.cpp文件

File wrapper-first.cpp:

#include "wrapper-first.h"
#include "first.h"

char* first::getName()
{
    return ::getName();
}

...并为第二个头文件创建相同的文件.然后,只需将crp文件中包含wrpper-include文件,并使用上面的代码即可.

...and create the same for the second header file. Then you just include the wrpper-include files in your cpp file and use the code as above.

这篇关于如何避免C ++中两个库的变量/函数冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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