gpt4 book ai didi

c - C 源文件中的外部结构

转载 作者:行者123 更新时间:2023-11-30 14:23:00 24 4
gpt4 key购买 nike

我试图在两个单独的 .c 文件中提供名为 dict_obj 的字典对象结构。这是在尝试为一个类编写 pthread TCP 服务器时的情况。我之前没有太多使用 C 语言,并且很难弄清楚这一点。我不确定我是否正确地将其声明为外部结构,因为 netbeans 在 clean 和 build 上抛出错误,指出未定义类型的无效使用。

在 db_functions.c 中我有:

//------------------------------------------------------------------------------
// Server Function & Variable Initialization
//------------------------------------------------------------------------------

struct dictionary_object dict_obj;


//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Server Function Codes:
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------



//------------------------------------------------------------------------------
// Database Initialization
//------------------------------------------------------------------------------

int db_initialization()
{

dict_obj.word_count = 0;
return 1;

在 db_operations.c 中我有:

struct dictionary_object
{
char dictionary[DICTIONARY_SIZE][WORD_LENGTH];
int word_count;
pthread_mutex_t dict_mutex;

};

extern struct dictionary_object dict_obj;

希望这能让你们充分了解我想要完成的任务,而不必用太多的代码让你们不知所措。提前致谢!如果您需要查看更多代码,请告诉我。

最佳答案

您需要在包含文件中定义一次结构内容和布局。还为那里的代码的所有函数和静态定义“外部”定义。在任何想要使用这些结构或定义的文件中,请包含头文件(例如 db_struct.h)。

db_struct.h:

struct dictionary_obhect {
char dictionary ...
}
extern struct dictionary_object dict_obj;
extern int db_initialization();

db_struct.c:

#include "db_struct.h"

struct dictionary_object dict_obj;
int db_initiatilization() {
dict_obc.word_count = 0;
}

请注意,这都是相当老式的 C 代码。现代 C++ 等有其他方法来做类似的事情。

关于c - C 源文件中的外部结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13300060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com