#include标头在程序集文件中的C声明没有错误?

And*_*ton 8 c x86 assembly gcc include

我有一个程序集文件(asm.S),它#define在C头文件(c_decls.h)中需要一个常量'd' .除了#define我想要的头文件包含C函数声明.不幸的是,gccbarfs在尝试编译汇编文件时.例如,

c_decls.h

#ifndef __c_decls_h__
#define __c_decls_h__

#define I_NEED_THIS 0xBEEF
int foo(int bar);

#endif
Run Code Online (Sandbox Code Playgroud)

asm.S

#include "c_decls.h"

.globl main
main:
    pushl %ebp
    movl %esp, %ebp
    movl $I_NEED_THIS, %eax
    leave
    ret
Run Code Online (Sandbox Code Playgroud)

产量

> gcc -m32 asm.S
c_decls.h:汇编程序消息:
c_decls.h:6:错误:表达式
c_decls.h 之后的垃圾'(int bar)' :6:错误:后缀或操作数对'int'无效

有没有办法在#include包含程序集文件中的函数声明的C头文件?(更改标题或移动/重新定义#define不是一个选项.)

pay*_*yne 11

使用-dM选项cpp只能从头文件中获取#defines,而是包含该文件.

cpp -dM c_decls.h > bare_c_decls.h
Run Code Online (Sandbox Code Playgroud)

现在包含bare_c_decls.h在.S文件中.如果您无法更改.S文件中的#include,请在另一个目录中生成裸头文件,并将该包含路径放在编译器/汇编器命令行上,而不是其他任何内容.

最后,您可以将其全部包装在makefile中,以便自动生成"裸"头文件.

  • 简单的“-dM”对我不起作用。它什么也不返回。`-E -dM` 转储所有定义,包括标头中定义的定义。唯一的不便是列表中有 700 多个定义。 (2认同)

小智 8

这就是问题:在.S文件中使用

#define __ASSEMBLY__
Run Code Online (Sandbox Code Playgroud)

在.C文件中使用

#undef __ASSEMBLY__
Run Code Online (Sandbox Code Playgroud)

然后在.h文件中放置条件

       #ifdef __ASSEMBLY__
                  // here declarations only for assembler
       #else
                  // here only for C
       #endif
                  // and here - defines suitable for both
Run Code Online (Sandbox Code Playgroud)

  • gcc foo.S已经将__ASSEMBLER__预先定义为1,因此您可以使用#ifndef __ASSEMBLER__保护所有纯C语言的东西。 (3认同)