我正在尝试完成“计算机科学基础,C 版”中的练习。下面的代码直接来自本书,但是当我尝试按照它们的描述包含和使用它时,我遇到了编译器错误。
#define DefCell(EltType, CellType, ListType)
typedef struct CellType *ListType;
struct CellType {
EltType element;
ListType next;
};
/*************************************************
* DefCell(int, CELL, LIST);
*
* expands to:
*
* typedef struct CELL *LIST;
* struct CELL {
* int element;
* LIST next;
* }
*
* as a consequence we can use CELL as the type of integer cells
* and we can use LISTas the type of pointers to these cells.
*
* CELL c;
* LIST l;
*
* defines c to be a cell and l to be a pointer to a cell.
* Note that the representation of a list of cells is normally
* a pointer to the first cell on the list, or NULL if the list
* is empty.
*
****************************************************/
(这本书可以免费下载 - 此代码在第 23 页。)
我也尝试过使用模板来解决其中一个练习(2.2.3):
DefCell(char, LETTER, STRING);
BOOLEAN FirstString(STRING s1, STRING s2);
我得到的错误是:
selectionsort.c:22:2: error: expected specifier-qualifier-list before ‘EltType’
selectionsort.c:60:28: error: expected ‘)’ before ‘s1’
selectionsort.c:133:28: error: expected ‘)’ before ‘s1’
我明白编译器不知道 STRING 或 EltType 是一个类型,但我不明白的是为什么不知道?这本书有点老了,所以 C 编程可能已经从书中的技术中走了出来。也有可能我只是误解了他们提出的想法的一些关键要素。 在我继续之前,我真的很想了解我做错了什么。谁能帮忙?
最佳答案
宏是“单行代码”。
新行结束宏。
需要告诉预处理器编辑器中的换行符不应该被视为一个。这是通过用反斜杠 (\
)结束行来完成的。
所以这个
#define DefCell(EltType, CellType, ListType)
typedef struct CellType *ListType;
struct CellType {
EltType element;
ListType next;
};
应该是
#define DefCell(EltType, CellType, ListType) \
typedef struct CellType * ListType; \
struct CellType { \
EltType element; \
ListType next; \
};
请注意,要实现此功能,在“行终止”反斜杠之后不允许。
顺便说一句:DefCell
不是可变参数宏。
#define DefCell(E, C, L, ...)
会是一个。
关于c - GCC 编译错误 : "error: expected specifier-qualifier-list before..." from variadic macro,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19571365/