This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
preprocessor expansion and defines
- From: Adam Mercer <ramercer at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Wed, 11 May 2011 13:41:05 -0500
- Subject: preprocessor expansion and defines
Hi
I'm trying to write a code that has several functions that are, more
or less, the same and only differ in the datatype on which they
operate. To minimise code duplication I'm trying to accomplish this
using the preprocessor and it's more or less working but I'm having
problems with one of the functions. The actual code is quite
complicated but I've reproduced the issue with a simple test code as
follows:
$ cat test.c
#include <stdio.h>
#define TYPECODE I8
#include "test_source.c"
#undef TYPECODE
int main()
{
I8_test();
return 0;
}
$ cat test_source.c
#define CONCAT2x(a,b) a##b
#define CONCAT2(a,b) CONCAT2x(a,b)
#define STRING(a) #a
#define FUNC CONCAT2(TYPECODE,_test)
int FUNC()
{
static int filenum=0;
char fname[FILENAME_MAX];
snprintf(fname, FILENAME_MAX, "%s_vector.%03d", \
STRING(TYPECODE), filenum++);
printf("%s: %s\n", __func__, fname);
return 0;
}
$ gcc test.c
$ ./a.out
I8_test: TYPECODE_vector.000
$
The problem is that I need the output of the code to be
I8_test: I8_vector.000
Looking at the output from cpp it seems like it should be doing the right thing:
int I8##_test()
{
static int filenum=0;
char fname[1024];
snprintf(fname, 1024, "%s_vector.%03d", #I8, filenum++);
printf("%s: %s\n", __func__, fname);
return 0;
}
But something is clearly wrong. Can anyone see what I'm doing wrong?
Cheers
Adam