首页 > 解决方案 > 在一个文件中定义变量,但在另一个文件中未定义(在公共头文件中声明)

问题描述

我有一些功能在单独的文件功能中突出显示。c。此文件中的代码读取位于functionality.h 中的阈值:

unsigned int thresold1[2];
unsigned int thresold2[2];
void *watcher(void *);

我也有 main.c 文件,我试图在其中配置这些阈值:

#include "functionality.h"

int main(void) {
    /* ... */
    int ret;
    pthread_t watcher_thread;
    thresold1[0] = 10;
    thresold1[1] = 50;
    ret = pthread_create(&watcher_thread, NULL, watcher, NULL);
    if (ret) {
        /* ... */
    }
    /* ... */
}

但是当我试图watcher()从function.c 中访问这些阈值时,所有这些数组值都归零,即未定义。我哪里错了?

PS 功能.h 也包含在功能.c 中

UPD:我是这样编译的:

gcc -pthread main.c functionality.c -o main

标签: ccompilationruntime-errorlinkage

解决方案


变量应在头文件中声明为:

extern unsigned int thresold1[2];
extern unsigned int thresold2[2];

并在一个独特的点(.c文件)中定义为:

unsigned int thresold1[2];
unsigned int thresold2[2];

推荐阅读