How to resolve two structures with the same name?

坚强是说给别人听的谎言 提交于 2019-12-22 05:28:59

问题


In my code base I find that two modules have structures with the same name. It is giving a name conflict error. Is there a way to resolve it without changing the code?


回答1:


This is a terrible hack, but it would be possible to use a macro to redefine the name of the struct, like so

// a.h
struct collide {
    int a;
};

// b.h
struct collide {
    float b;
};

// test.c
#define collide a_collide
#include "a.h"
#undef collide
#include "b.h"
int main(){
    struct a_collide a;
    struct collide b;
    return 0;
}

You'd probably want to rename the struct for both headers to give errors when someone inevitably uses the wrong struct, perhaps in a wrapper header like

// wrap_a.h
#define collide a_collide
#include "a.h"
#undef collide

Remember to undef the macro so you don't get random replacements throughout your code.




回答2:


No really good ideas come to mind. Here are two not-so-good ones:

  • If you are very lucky, you can segregate your code so that no module every needs to access both types of structure at one time, then only include the proper header, and away you go. This is fraught with peril and will be a maintainability nightmare: anyone who comes after you will have cause to curse your name and all your descendants unto the seventh generation.

  • If the code is c89ish you could try compiling with a c++ compiler and wrapping one or more of the offending structures in a namespace. This introduces problems from all the picky little differences in the two language (casting rules, class as a reserved word, etc...), so it almost certainly violates your request to not change the code.

Good luck.



来源:https://stackoverflow.com/questions/2680502/how-to-resolve-two-structures-with-the-same-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!