【发布时间】:2011-10-18 20:03:46
【问题描述】:
我正在用 C 实现队列的实现。我的界面包含五个简单的函数来访问队列:
#ifndef QUEUE_H
#define QUEUE_H
#include <stdbool.h>
#include <stddef.h>
struct queue {
struct cell* first;
struct cell* last;
};
typedef struct queue queue;
extern queue newQueue(void);
extern bool isEmpty(queue);
extern queue enqueue(queue,void*);
extern queue dequeue(queue);
extern void* front(queue);
extern void freeQueue(queue);
由于其中两个(newQueue 和 isEmpty)非常简单,我相信编译器可以对它们进行很多很好的优化,因此我决定为它们编写内联声明:
/* replacing the two lines
extern queue newQueue(void);
extern bool isEmpty(queue);
in the original header */
extern inline queue newQueue(void) {
queue q = { NULL, NULL };
return q;
}
extern inline bool isEmpty(queue q) {
return q.first == NULL;
}
使用 gcc 可以很好地编译。但是当我用clang编译它时,它给了我一个错误。一项快速研究表明,从 GNU 样式执行这些内联声明 is different 的官方方式。我可以通过-std=gnu89 或根据上面的链接更改函数签名。我选择了第二个选项:
inline queue newQueue(void) {
queue q = { NULL, NULL };
return q;
}
inline bool isEmpty(queue q) {
return q.first == NULL;
}
但是现在,当在 c99 模式下编译时,clang 和 gcc 都谈到了重复的函数声明。这是queue.c中的随附定义:
#include "queue.h"
/* ... */
queue newQueue() {
queue q = { NULL, NULL };
return q;
}
bool isEmpty(queue q) {
return q.first == NULL;
}
我做错了什么?如何在不需要切换到 gnu89 模式的情况下得到我想要的?
这些是我使用第二种样式时收到的错误消息:
$ gcc -std=c99 queue.c
queue.c:12:7: error: redefinition of ‘newQueue’
queue.h:14:21: note: previous definition of ‘newQueue’ was here
queue.c:17:6: error: redefinition of ‘isEmpty’
queue.h:19:20: note: previous definition of ‘isEmpty’ was here
$ clang -std=c99 queue.c
queue.c:12:7: error: redefinition of 'newQueue'
queue newQueue() {
^
In file included from queue.c:5:
./queue.h:14:21: note: previous definition is here
extern inline queue newQueue(void) {
^
queue.c:17:6: error: redefinition of 'isEmpty'
bool isEmpty(queue q) {
^
In file included from queue.c:5:
./queue.h:19:20: note: previous definition is here
extern inline bool isEmpty(queue q) {
^
2 errors generated.
【问题讨论】:
-
您能否显示您收到的exact 错误消息? “关于重复函数定义的一些事情”不够具体。
-
@Greg 抱歉忘记了错误信息。我已经添加了。