0
%macro printhello 0
  section .rodata
  %%msg:  db  "Hello, world.", 10, 0
  section .text
       push  %%msg
       call  printf
       add   esp, 4
%endmacro

The problem is that every time the macro appears in the program, NASM preprocessor will invent a new name for the label msg and there will be multiple definitions of the same string "Hello, world." I could define the string without the %% prefix, but if the macro will be used more than once, I will get an assembly error for redefining the same symbol, msg. So how can I avoid multiple definitions of that string?

Ori Popowski
  • 10,432
  • 15
  • 57
  • 79

2 Answers2

3

You could do something like this:

%macro printhello 0
  %ifndef HelloWorldMsg
  %define HelloWorldMsg
  section .rodata
HWM:   db    "Hello, world.", 10, 0
  %endif
  section .text
       push  HWM
       call  printf
       add   esp, 4
%endmacro
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
  • Note that `section .text` will switch to the `.text` section even if that wasn't the section that was active at the point the macro was called, probably breaking the surrounding code. – BeeOnRope Oct 25 '17 at 02:26
  • You can switch back to the original section instead of unconditionally to `.text` as shown in https://nasm.us/doc/nasmdoc7.html#section-7.3 / [NASM Specific -- Section vs \[SECTION \]](https://stackoverflow.com/q/5925797) – Peter Cordes Jan 06 '22 at 05:03
  • This include-guard idea to avoid repeated definition is a good one. If you have *different* data for different instances of the macro, you can use `%%HWM:` and `push %%HWM` to get a label name unique to each expansion of the macro. – Peter Cordes Jan 06 '22 at 05:05
2

I'm not sure I see the point of putting "hello world" in the macro. I should think you'd want to pass the text to print as a parameter to the macro, no?

%macro printhello 1
section .rodata
%%msg:  db  %1, 10, 0
section .text
   push  %%msg
   call  printf
   add   esp, 4
%endmacro

section .text
_start ; (?)
printhello "hello world"
printhello "goodbye cruel world"

That's untested, but "something like that"...

Best, Frank