Home > OS >  Problems in pre-processor directive (Macro) using gcc in Code::Blocks
Problems in pre-processor directive (Macro) using gcc in Code::Blocks

Time:11-11

#include<stdio.h>
#include <string.h>

#define STR1 "F:\\c\\projects\\Banking Management System\\data\\"
#define STR2 "pwd.txt"

#define STR3 STR1 STR2

#define PPCAT_NX(A, B) A##B
#define PPCAT(A, B) PPCAT_NX(A, B)


void main() {
    printf("\n%s", STR3);
    printf("\n%s ",PPCAT(STR1, STR2));
}

PROBLEM STATEMENT

The first ("printf("\n%s", STR3);") works fine giving me the desired output as follows:

F:\c\projects\Banking Management System\data\pwd.txt

However, the 2nd (printf("\n%s ",PPCAT(STR1, STR2));" gives me the folloiwng error:

|=== Build file: "no target" in "no project" (compiler: unknown) ===| F:\c\projects\Banking Management System\src\stringConcatMacro.c||In function 'main':| F:\c\projects\Banking Management System\src\stringConcatMacro.c|4|error: pasting ""F:\c\projects\Banking Management System\data\"" and ""pwd.txt"" does not give a valid preprocessing token| F:\c\projects\Banking Management System\src\stringConcatMacro.c|9|note: in definition of macro 'PPCAT_NX'| F:\c\projects\Banking Management System\src\stringConcatMacro.c|15|note: in expansion of macro 'PPCAT'| F:\c\projects\Banking Management System\src\stringConcatMacro.c|15|note: in expansion of macro 'STR1'| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

I want to use the 2nd method wherein I could pass different file names (instead of using fixed STR2) with my path (STR1).

Where are the things going wrong with the 2nd option? enter code here

Any, help would be most appreciated.

CodePudding user response:

Where are the things going wrong with the 2nd option?

The rule is that the result of ## has to be a "valid token". STR1 is a token, a number 1234 is a token, a string literal "string" is also an example of a token. The result of ## joining two string literals like "string""string" is not a single valid token. So the operation is invalid.

String literals are joined together anyway, just write them side by side.

#define STRLITERALCAT(a, b)  a b
  • Related