user3016320
user3016320

Reputation: 59

How do I concatenate #define value?

I have following definitions

#define ID valve1

#define PROJECT "..\"+ID+"_data_var.h"

when I print PROJECT it should give below result

"..\valve1_data_var.h"

It means definition PROJECT should have "..\valve1_data_var.h"

Upvotes: 2

Views: 3853

Answers (5)

glglgl
glglgl

Reputation: 91017

At first glance I would have thought about the ## as well. It concatenates identifiers in order to form a larger one:

#define CONCATHELP(a,b,c) a##b##c
#define CONCAT3(a,b,c) CONCATHELP(a,b,c)
#define CONCAT2(a,b,c) CONCATHELP(a,,c)

#define STD(what) CONCAT2(std,what)
#define mysink err

...

fprintf(STD(mysink), ...) // prints to stderr

But in your case, you need the stringifying # operator which turns a parameter into its argument's representation:

#define mkstr(s) #s

mkstr(foo) // is the same as "foo"

So in your case,

#define PROJX(id) "..\\" #id "_data_var.h"
#define PROJ(id) PROJX(id)
#define PROJECT PROJ(ID)

might be one way to go. Another alternative is

#define mkstrX(s) #s
#define mkstr(s) mkstrX(s)
#define PROJECT "..\\" mkstr(ID) "_data_var.h"

which does the same, getting a result of

"..\\" "valve1" "_data_var.h"

which, in turn, is understood by the compiler as the concatenation of the components.

The additional level of indirection is needed to help to become the ID mapping to valve1 to become effective.

Upvotes: 1

user207064
user207064

Reputation: 665

#include<stdio.h>
#define ID "valve1"

#define PROJECT(A,B,C) #A B #C
main()
{
       printf("%s\n", PROJECT(../,ID,_data_var.h));
       return;
}

Hope this helps

Upvotes: 0

Arjun Sreedharan
Arjun Sreedharan

Reputation: 11453

You can generally use the ## (double number sign) to concatenates two tokens in a macro invocation.

However, since you have string literals jamming an already defined macro, you could just use spaces, else you could run into invalid preprocessing token.

Also, you should escape your backslash.

#define ID "valve1"

#define PROJECT "..\\" ID "_data_var.h"

Upvotes: 2

user694733
user694733

Reputation: 16043

#define PROJECT3(x) # x
#define PROJECT2(x) PROJECT3(x)
#define PROJECT "..\\" PROJECT2(ID) "_data_var.h"

It creates literal "..\\" "valve1" "_data_var.h" which compiler sees as a single string "..\\valve1_data_var.h".

Upvotes: 0

catbert
catbert

Reputation: 1017

C preprocessor defines support token concatenation:

http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

Basically, you use ## instead of +:

#define PROJECT "..\"##ID##"_data_var.h"

Upvotes: 0

Related Questions