【问题标题】:Share a global structure between two files (in C)在两个文件之间共享一个全局结构(在 C 中)
【发布时间】:2017-08-24 12:27:58
【问题描述】:

我有两个文件,main.c 和 hash.c

在 hash.c 中,我只有一个名为 hashtable 的空哈希表和一些函数(不是主函数) 在 main.c 中,我有 main() 函数和 #include "hash.h"

我的问题是,如果在 main.c 中,我从 hash.c 中调用一个函数,例如:hash_add("strawberry", 3),它在 hash.c 的哈希表中添加一个键及其元素(称为 @987654324 @),

如果我在 main.c 中执行 extern hash * hashtable,我的 3 个草莓会在哈希表中吗?还是我的哈希表是空的?

(我的想法是,当我调用hash_add("strawberry", 3) 时,只要我在函数范围内,我的 3 个草莓就在哈希表中)

谢谢

【问题讨论】:

  • 如果你在 hash.c 中有hash *hastable;,你必须在你想使用变量的每个其他文件中写extern hash *hashtable;

标签: c file structure share global


【解决方案1】:

在 C 中有两种方法可以做到这一点。听起来您正在使用全局变量,所以我将首先描述它。更好的方法是使用局部变量,我会告诉你第二个:

使用全局变量,您可以这样做:

// hash.h
void hash_add(const char* key, int value);
extern hash h;

// hash.c
hash h;
void hash_add(const char* key, int value) { ... }

// main.c
#include "hash.h"
int main()
{
    hash_add("strawberry", 3);
    // h will now have three strawberries
}

最好不要使用全局变量,因为这样会减少名称冲突,并且一次可以有多个哈希表。在这种情况下,您通常会持有一个指向哈希的指针,然后将其传递给哈希函数:

// hash.h
void hash_add(hash* h, const char* key, int value);
hash* hash_create();
void hash_destroy(hash* h);

// main.c
#include "hash.h"
int main()
{
    hash* h = hash_create();

    hash_add(h, "strawberry", 3);
    // h will now have three strawberries

    hash_destroy(h);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2015-03-28
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多