How to access C preprocessor constants in assembly?

谁说胖子不能爱 提交于 2019-12-21 19:11:06

问题


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

#define constant 1

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


回答1:


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.




回答2:


You can't, unless a specific development chain allows it. But in 20 years or so of embedded programming I never saw one.

Usually, the only way for assembly and C to communicate is the linker, i.e. labels defined in C/C++ are accessable from within assembly (and vice versa).

When I had to share definitions between C/C++ and asm, I usually did it with a custom code generator.

Since high-level data are rarely exchanged with assembly, a few defines and maybe some external references are usually enough, and thus the code generator is really easy to make.

You can use for instance perl or awk to parse a very simple list of common constants and produce a pair of files, one with #defines and the other with the equivalent EQU directives.



来源:https://stackoverflow.com/questions/21276255/how-to-access-c-preprocessor-constants-in-assembly

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