Home > Mobile >  Define variable in one file but it's undefined in another (declared in common header)
Define variable in one file but it's undefined in another (declared in common header)

Time:10-04

I have some functionality which is highlighted in a separate file functionality.c. The code in this file reads thresholds which are in functionality.h:

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

Also I have main.c file, where I'm trying to configure these thresholds:

#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) {
        /* ... */
    }
    /* ... */
}

But when I'm trying to access these thresholds in watcher() from functionality.c all these array values are zeroed, i.e. undefined. Where am I wrong?

P.S. functionality.h is also included to functionality.c

UPD: I compile it such a way:

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

CodePudding user response:

Variable should be declared in the header file as:

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

and defined in a unique point (.c file) as:

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