This page is a mirror of Tepples' nesdev forum mirror (URL TBD).
Last updated on Oct-18-2019 Download

Connecting variable names in macros

Connecting variable names in macros
by on (#194616)
In C, there's a neat feature that lets you put together variable names.

For example, if you write:
Code:
#define NumberA 1
#define NumberB 2

#define GetNum(name) (Number##name)

and you call the macro like this:
Code:
int i = GetNum(A);
then the preprocessor will transform it into
Code:
int i = NumberA;


Now, I want to do something similar in Assembly with cc65:

I'd like to create a macro to declare variables that have to be exported for Assembly and for C.

So, instead of this:
Code:
SomeVariable: .res 1
.export SomeVariable
.export _SomeVariable = SomeVariable

I want to write this:
Code:
DECLARE_GLOBAL SomeVariable, 1

And the macro shall look like this:
Code:
.macro DECLARE_GLOBAL name, size
    name: .res size
    .export name
    .export _##name = name
.endmacro

Is this possible?
Re: Connecting variable names in macros
by on (#194618)
DRW wrote:
Is this possible?

Yes. This should work (not tested):

Code:
.macro DECLARE_GLOBAL name, size
    name: .res size
    .export name
    .export .ident(.sprintf("_%s", .string(name))) = name
.endmacro
Re: Connecting variable names in macros
by on (#194619)
Thanks. This works.
Re: Connecting variable names in macros
by on (#194638)
You do know that asm can use the C vars fine?

_SomeVariable: .res 1

Sure, it's an extra _ when using it in asm.
Re: Connecting variable names in macros
by on (#194641)
Yes, I know. But I prefer clean variable names. That's why I always declare them with a regular name and only export them with the underscore.
Also, when I notice that a certain variable doesn't need to be exported to C and therefore doesn't need an underscore, I don't have to rename every occurence of it.