Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access C preprocessor constants in assembly?

If I define a constant in my C .h file:

#define constant 1

How do I access it in my assembly .s file?

like image 382
user2378481 Avatar asked Dec 26 '22 14:12

user2378481


1 Answers

If you use the GNU toolchain, gcc will by default run the preprocessor on files with the .S extension (uppercase 'S'). So you can use all cpp features in your assembly file.

There are some caveats:

  • there might be differences in the way the assembler and the preprocessor tokenize the input.
  • If you #include header files, they should only contain preprocessor directives, not C stuff like function prototypes.
  • You shouldn't use # comments, as they would be interpreted by the preprocessor.

Example:

File definitions.h

#define REGPARM 1

File asm.S

#include "definitions.h"

.text
.globl relocate

    .align 16
    .type relocate,@function
relocate:
#if !REGPARM
    movl  4(%esp),%eax
#endif
    subl  %ecx,%ecx
    ...

Even if you don't use gcc, you might be able to use the same approach, as long as the syntax of your assembler is reasonably compatible with the C preprocessor (see caveats above). Most C compilers have an option to only preprocess the input file (e.g. -E in gcc) or you might have the preprocessor as a separate executable. You can probably include this preprocessing prior to assembly in your build tool.

like image 78
Chris Avatar answered Dec 28 '22 03:12

Chris