C中的文件描述符。将它们与静态全局相关联

时间:2016-06-21 01:19:34

标签: c variables

如果我正在编写一个使用文件描述符进行处理的库,那么何时应该从lib_init()返回它以使用更高层代码并传递给我的lib_do_stuff()调用,以及何时我可以将它作为私人“成员”留在我的C库中作为.c文件中的静态全局吗?

如果我不认为我的库的用户应该控制甚至访问文件描述符,我可以保留它,就像在C ++中那样只是private吗?

以这种方式做到这一点有什么缺点?

1 个答案:

答案 0 :(得分:3)

用一个例子扩展我的建议。

您的图书馆需要两个(至少)标题文件:您的图书馆用户包含的一个公开文件,以及仅包含在图书馆源文件中的一个私人文件。

公众可能像

#pragma once

// This is all that is needed to declare pointers to the internal structure
typedef struct internal_structure STRUCTURE;

// The public API of your library
STRUCTURE *lib_init(void);
void lib_cleanup(STRUCTURE *s);
...

然后你有私人头文件

#pragma once

struct internal_structure
{
    int fd;
    // Other members as needed
    ...
};

// Possible function prototypes of private functions

然后在您的库源文件中包含公共和私有头文件,并使用STRUCTURE作为黑盒结构:

#include <stdlib.h>
#include "public.h"
#include "private.h"

STRUCTURE *lib_init(void)
{
    STRUCTURE *s = malloc(sizeof *s);
    s->fd = open(...);
    // Other initialization
    ...
    return s;
}

void lib_cleanup(STRUCTURE *s)
{
    // Other cleanup
    ...
    close(s->fd);
    free(s);
}

然后,您的库的用户只包含公共头文件,并使用您定义良好的API:

#include "public.h"

int main(void)
{
    STRUCTURE *s = lib_init();
    ...
    lib_cleanup(s);
    return 0;
}

公共函数都应该将STRUCTURE *作为它们的一个参数,通常是它们的第一个参数,类似于lib_cleanup函数。然后,该函数可以以任何方式使用结构及其成员。

相关问题