You need to stringize TYPECODE twice, or you'll get (as you are presently) #TYPECODE: #define STRING2(a) STRING(a) #define STRING(a) #a ... snprintf(fname, FILENAME_MAX, "%s_vector.%03d", STRING2(TYPECODE), filenum++); ... John G On Wed, May 11, 2011 at 7:41 PM, Adam Mercer <ramercer@xxxxxxxxx> wrote: > 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 >