nesdev.com
http://forums.nesdev.com/

Connecting variable names in macros
http://forums.nesdev.com/viewtopic.php?f=2&t=15876
Page 1 of 1

Author:  DRW [ Sat Apr 29, 2017 3:10 pm ]
Post subject:  Connecting variable names in macros

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?

Author:  thefox [ Sat Apr 29, 2017 3:30 pm ]
Post subject:  Re: Connecting variable names in macros

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

Author:  DRW [ Sat Apr 29, 2017 3:45 pm ]
Post subject:  Re: Connecting variable names in macros

Thanks. This works.

Author:  calima [ Sun Apr 30, 2017 2:34 am ]
Post subject:  Re: Connecting variable names in macros

You do know that asm can use the C vars fine?

_SomeVariable: .res 1

Sure, it's an extra _ when using it in asm.

Author:  DRW [ Sun Apr 30, 2017 4:59 am ]
Post subject:  Re: Connecting variable names in macros

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.

Page 1 of 1 All times are UTC - 7 hours
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/