简体   繁体   中英

C compiling error: stray '##' in program

I was working with an embedded kernel source when I saw something like this:

#define OMAP_SYS_TIMER_INIT(name, clkev_nr, clkev_src, clksrc_nr, clksrc_src) \
static void __init omap##name##_timer_init(void)                              \
{                                                                             \
    omap2_gp_clockevent_init((clkev_nr), clkev_src);                          \
    omap2_gp_clocksource_init((clksrc_nr), clksrc_src);                       \
}

and when I tryed to make a program that used this ## thing (that I don't know the name) to see what it could really do I didn't got it to work. Below is what I did to test it's function. I just want to see if the argument inside the ## is literal or not, but something is clearly missing in my code for it to compile...

#include <stdio.h>
#include <stdlib.h>

#define DEFINE_1 2
#define DEFINE_2 4
#define DEFINE_3 6

#define DEFINE_i 9

int main(void)
{
  int i;
  for(i=1;i<4;i++) {
    printf("numero %d = %d\n",i,DEFINE_##i##);
  }
  return EXIT_SUCCESS;
}

The output of gcc is:

test.c: In function ‘main’:
test.c:14:5: error: stray ‘##’ in program
test.c:14:33: error: ‘DEFINE_’ undeclared (first use in this function)
test.c:14:33: note: each undeclared identifier is reported only once for each function it appears in
test.c:14:42: error: expected ‘)’ before ‘i’
test.c:14:42: error: stray ‘##’ in program

Anyone knows what is wrong? Thanks

It's the token concatenation operator for the C preprocessor. The reason your example doesn't compile is because you're not using the ## operator within a macro (ie #define statement).

Here's another post with some more information.

## means concatenation at time of preprocessing. http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

您只能在预处理程序指令中使用##。

## is used for concatenation in C preprocessor macros .

In your example, the idea is to concatenate omap with the function name. For example

OMAP_SYS_TIMER_INIT(foo, ...)

will create a function named omapfoo.

## is token pasting operator and you can only use it in a macro definition. You cannot use it outside a macro definition.

Maybe what you are trying to do is, DEFINE_ and (i=1) will concatenate using ## to form "DEFINE_1" and that will be your macro with value 2. Right? If that's the case, the problem is that, macro is preprocessor and value will be get in lined before execution. So it looks for DEFINE_i and there is no such macro. Keep it in mind i=1,2,3.. and so on during runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM