fuz*_*fuz 3 c gcc inline c99 clang
我在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);
Run Code Online (Sandbox Code Playgroud)
由于其中两个(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;
}
Run Code Online (Sandbox Code Playgroud)
用gcc编译好.但是当我用clang编译它时,它给了我一个错误.一项快速研究表明,这些内联声明的官方方式与GNU风格不同.我可以-std=gnu89根据上面的链接传递或更改功能签名.我选择了第二个选项:
inline queue newQueue(void) {
queue q = { NULL, NULL };
return q;
}
inline bool isEmpty(queue q) {
return q.first == NULL;
}
Run Code Online (Sandbox Code Playgroud)
但是现在,当以c99模式编译时,clang和gcc都会说一些关于重复函数声明的内容.这是随附的定义queue.c:
#include "queue.h"
/* ... */
queue newQueue() {
queue q = { NULL, NULL };
return q;
}
bool isEmpty(queue q) {
return q.first == NULL;
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?如何在不需要切换到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.
Run Code Online (Sandbox Code Playgroud)
如果要在标题中定义函数,请创建它们static.这应该足以让编译器内联它们(inline只是一个额外的提示).
static如果在整个程序中包含多个标题,则标题中的非函数将导致多个定义.
我做了一些研究并获得了更多信息:
你可以这样使用inline.至少在C99.你不能同时拥有内联和非内联定义queue.c.您需要包含内联定义#ifdef或将其移动到未包含在内的标题中queue.c.
您需要编写两次函数并使用预处理器,但它应该完全按照您的意愿工作.当函数未内联时,它只会被发出一次.
| 归档时间: |
|
| 查看次数: |
2842 次 |
| 最近记录: |