英文:
Creative way for converting __attribute__ ((packed)) with visual cpp pragma
问题
我正在进行一个项目,需要将一个庞大的嵌入式目标上运行的C代码库转换为Visual C++软件。C代码中的所有结构体都是用__attribute__ ((pack))
定义的,而Visual C++不支持这个语法。我无法修改C代码。
我正在寻找一种方法,使得vc++可以像它处理pragma pack
宏一样处理__attribute__ ((packed))
。简单地用宏定义替换这两者的方法不可行,因为__attribute__ ((packed))
宏的两个单词之间有一个空格,并且第二个单词以(
开头。
有没有其他创造性的方法,而不需要我修改代码呢?
英文:
I'm working on a project which requires converting a massive codebase from c running on embedded target to a visual c++ software, all of the structures in the c code are defined with __attribute__ ((pack))
which visual c++ does not support,
I cannot alter the c code.
I am looking for a workaround which will enable me to make vc++ refer to __attribute__ ((packed))
the same way as it refers pragma pack,pop macros
the simple method of a define substituting the two is not possible because the __attribute__ ((packed))
macro has a space between its words and the second word starts with a '('
is there any other creative way that won't make me alter the code?
答案1
得分: 1
首先,我建议您自己思考一下,在VC编译版本的代码中,是否需要对结构进行紧凑排列?这是否有功能上的原因,还是仅仅是原始编码者的个人喜好?
其次,代码是否使用了其他 __attribute__
指令?如果没有,那么您可以安全地通过定义一个空宏来“移除”所有的 gcc __attribute__
指令,方法如下:
#define __attribute__(...)
可以将这行代码放在一个“强制包含”头文件中(命令行选项 /FI <filename>
),或者直接在命令行中添加:
/D __attribute__(...)
如果只有一个用途是用于紧凑排列的 __attribute__
,而您实际上并不需要紧凑排列的结构,那么您已经完成了。如果紧凑排列是必要的,正如您所说:
c代码中的所有 结构都是[紧凑排列]
那么,您可以通过在项目中使用 /Zp
命令行选项全局应用紧凑排列,或者在强制包含文件中添加:
#pragma pack(1)
如果这个解决方案并不完全适合——例如,并非所有结构都应该紧凑排列,或者 __attribute__
用于其他目的并且是必需的——那么最简单的解决方法可能是在Windows构建中使用GCC而不是VC。最简单的方法是使用MinGW(Windows的极简GNU)。
英文:
First of all, I would ask yourself whether in the VC compiled version of the code the structures need to be packed? Is there a functional reason for this, or just the whim of the original coder?
Secondly does the code use any other __attribute__
directives? If not then you can safely "remove" all the gcc __attribute__
directives by defining an empty macro, either:
#define __attribute__(...)
in a "forced-include" header file (command line option /FI <filename>
), or simply:
/D __attribute__(...)
on the command line. The forced-include may be simpler if you need to add other directives to adapt the code.
So if the only use of __attribute__
is for packing, and you don't really need packed structures, then you are done. If however the packing is essential, and as you say:
> all of the structures in the c code are [packed]
Then you can globally apply packing via the command line using /Zp
for the project, or in the forced-include file add:
#pragma pack(1)
If the solution is not truly suitable - for example not all the structures should be packed or __attribute__
is used (and needed) for other purposes - then the path of least resistance may be to use gcc rather then VC for your Windows build. The easiest way to do that is to use MinGW (minimal GNU for Windows).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论