#include header with C declarations in an assembly file without errors?
Solution 1
Use the -dM
option for cpp
to get just the #defines out of your header files, and include that file instead.
cpp -dM c_decls.h > bare_c_decls.h
Now include bare_c_decls.h
in your .S file. And if you can't change the #include in the .S file, generate the bare header files in another directory, and put that include path on your compiler/assembler command line, ahead of everything else.
And finally, you can wrap this all up in a makefile so your "bare" header files are generated automatically.
Solution 2
That's simle: In your .S file use
#define __ASSEMBLY__
In your .C file use
#undef __ASSEMBLY__
Then in .h file place condition
#ifdef __ASSEMBLY__
// here declarations only for assembler
#else
// here only for C
#endif
// and here - defines suitable for both
Related videos on Youtube
Andrew Keeton
Updated on February 26, 2020Comments
-
Andrew Keeton about 4 years
I have an assembly file (
asm.S
) which needs a constant#define
'd in a C header file (c_decls.h
). The header file contains C function declarations in addition to the#define
I want. Unfortunately,gcc
barfs when trying to compile the assembly file. For example,c_decls.h
#ifndef __c_decls_h__ #define __c_decls_h__ #define I_NEED_THIS 0xBEEF int foo(int bar); #endif
asm.S
#include "c_decls.h" .globl main main: pushl %ebp movl %esp, %ebp movl $I_NEED_THIS, %eax leave ret
Output
> gcc -m32 asm.S
c_decls.h: Assembler messages:
c_decls.h:6: Error: junk '(int bar)' after expression
c_decls.h:6: Error: suffix or operands invalid for 'int'Is there a way to
#include
a C header file that contains function declarations in an assembly file? (Changing the header or moving/redefining the#define
is not an option.) -
user3124812 about 7 yearsHeader should be included with 'C' like include,
#include my_defs.h
, not 'ASM' like.include my_defs.h
. In last case#ifdef
,#else
,#endif
will be ignored by asm parser. Just stumble over this... -
user3124812 about 7 yearsSimple
-dM
doesn't work for me. It returns nothing.-E -dM
dumps all defines, including one which is defined in a header. There only inconvenience that there are more than 700 defines in the list. -
payne about 7 yearsWhat version of cpp are you using? (Note the question is related to gcc)
-
user3124812 about 7 yearsIt's GNU GCC,
arm-none-eabi-g++ (GNU Tools for ARM Embedded Processors) 4.9.3 20150529 (release)
-
Peter Cordes over 6 years@user3124812: You probably ran
gcc -dM
rather thancpp -dM
. You should usegcc -E -dM
with all other compile options you normally use, to make sure all#ifdef
s in your headers get the same pre-defined macros. (e.g. maybe you have#ifdef __AVX__
in a header, and define something differently if building on an x86 target with-mavx
vs. without.) So I'd recommend not usingcpp
directly. -
Peter Cordes over 6 years
gcc foo.S
already pre-defines__ASSEMBLER__
to 1. So you can just protect all your C-only stuff with#ifndef __ASSEMBLER__