首页 > 解决方案 > 如何解决头文件中的变量冲突?

问题描述

我正在 OpenSees(主要用 Visual Studio C++ 编写的开源地震工程模拟项目)中编写自适应步长更新算法。我面临两个不同头文件(即windef.hsteelz01.h)中具有相同名称的两个变量之间的冲突。我需要一种方法来解决这个冲突。

我在我的项目中使用gnuplot-iostream.h,只有当我包含这个头文件时我才会面临这个冲突,否则没有冲突,代码是完美的。

基本上gnuplot-iostream.h正在调用windows.h,这进一步调用了 windef.h。我在 steelz01.h 文件中添加了 include gauards,但它没有解决问题。

当我将 steelz01.h 中的 varaibale 名称更改为其他名称时,代码也正在完美构建。未找到任何问题。但是,我不想在 steelz01 中更改变量的名称,它会产生严重的影响。

我包括这样的头文件

#include "gnuplot-iostream.h"
#include <SteelZ01.h>

这就是在 steelz01 中定义变量 SIZE 的方式

#define LOOP_NUM_LIMIT               30
const int SIZE = LOOP_NUM_LIMIT; //limit of array number

在windef.h中,它是这样定义的

typedef struct tagSIZE
{
    LONG        cx;
    LONG        cy;
} SIZE, *PSIZE, *LPSIZE;

typedef SIZE               SIZEL;
typedef SIZE               *PSIZEL, *LPSIZEL;

Visual Studio 2017 抛出此错误,

1>c:\program files (x86)\windows kits\8.1\include\shared\windef.h(190): error C2378: 'SIZE': redefinition; symbol cannot be overloaded with a typedef

1>e:\phd working folder\0_ops_github\src\material\nd\reinforcedconcreteplanestress\steelz01.h(17): note: see declaration of 'SIZE'

我期待一种解决此冲突的方法并成功构建。

标签: c++visual-studio-2017

解决方案


我建议您将 include 语句放在命名空间中,

namespace ABC
{
    #include "gnuplot-iostream.h"
}

namespace PQR
{
   #include <SteelZ01.h>
}

称呼:

ABC::SIZE
PQR::SIZE

这不会更改现有库的任何代码。但是,使用通用名称的库的作者因此建议他将通用名称保留在命名空间下以减少任何冲突。


推荐阅读