error: expected ')' before numeric constant

学习Linux C时遇到的问题,地址:https://akaedu.github.io/book/ch21s04.html

 

写一个assert函数

/* main.c */

#include "xassert.h"

#include 
#include 

int main(void)
{
	assert(2>3);
	
	return 0;
}

 

/* xassert.h */

#undef assert

#ifdef NDEBUG
	#define assert(test) ((void)0)
#else
	void _Assert(char*);
	
	#define _STR(x) _VAL(x)
	#define _VAL(x) #x
	#define assert(test) ( (test)?(void)0:_Assert( __FILE__ ":" _STR(__LINE__) " " #test) )
	
#endif





/* xassert.c */

#include 
#include 

#include "xassert.h"

void _Assert(char* msg)
{
	fputs(msg, stderr);
	fputs(" -- Assertion failed!", stderr);
	abort();
}

 

 

后来发现是这句的问题

#define assert(test) ( (test)?(void)0:_Assert( __FILE__ ":" __LINE__ " " #test) )

__LINE__展开为当前代码行的行号

改成:

#define assert(test) ( (test)?(void)0:_Assert( __FILE__ ":" _STR(__LINE__) " " #test) )

改成这也可以:

#define assert(test) ( (test)?(void)0:_Assert( __FILE__ ":" _VAL(__LINE__) " " #test) )

不是很明白,为什么要下面这样把一个数字转两道

	#define _STR(x) _VAL(x)
	#define _VAL(x) #x

 

最终结果:

你可能感兴趣的:(Linux)