ALUE) printf("File %s line %d: "\
#VALUE " = " FORMAT "\n"\
,__FILE__, __LINE__,VALUE\
);
enum {
RET_OK,
RET_FAIL
};
GNERIC_PRINT(int, "%d", _int)
GNERIC_PRINT(float, "%f", _float)
GNERIC_PRINT(char *, "%s", _str)
int main(void)
{
int i = 0;
float f = 2.6;
char *test = "Generics test!";
#if DEBUG
DEBUG_PRINT("%f", f)
#endif
PRINTSTAT( "%s", "Integer")
for(; i<10; i++)
print_int(i);
printf("\n");
PRINTSTAT( "%s", "Float")
print_float(f);
printf("\n");
PRINTSTAT( "%s", "String")
print_str(test);
printf("\n");
return RET_OK;
}
Makefile
[html]
OBJS = printtest.o
TARGET = printtest
SRC = printtest.c
all:$(OBJS)
gcc -g $(OBJS) -o $(TARGET)
$(OBJS):printtest.s
gcc -g -c printtest.s -o $(OBJS)
printtest.s:printtest.i
gcc -g -S printtest.i -o printtest.s
printtest.i:$(SRC)
gcc -g -E $(SRC) -o printtest.i
clean:
rm *~ *.o *.s *.i $(TARGET)
OBJS = printtest.o
TARGET = printtest
SRC = printtest.c
all:$(OBJS)
gcc -g $(OBJS) -o $(TARGET)
$(OBJS):printtest.s
gcc -g -c printtest.s -o $(OBJS)
printtest.s:printtest.i
gcc -g -S printtest.i -o printtest.s
printtest.i:$(SRC)
gcc -g -E $(SRC) -o printtest.i
clean:
rm *~ *.o *.s *.i $(TARGET)
*SRC = printtest.c,而不是SRC=printtest.c printtest.h。后者,不能正确完成预处理,此处颇让人费解。有人能说明原因吗?
或采用
[html]
gcc printtest.h printtest.c -o printtest
gcc printtest.h printtest.c -o printtest
进行编译
【运行结果】
[html]
**************** Integer Test ****************
0123456789
**************** Float Test ****************
2.600000
**************** String Test ****************
Generics test!
**************** Integer Test ****************
0123456789
**************** Float Test ****************
2.600000
**************** String Test ****************
Generics test!www.2cto.com
这种方法看似很炫,但在代码量巨大的情况下,非常容易出错。因此推荐采用函数指针的形式实现泛型。
作者;tandesir