Question

I want to create a library in C using MPLAB X IDE(ide for PIC developing).

My library ABCLib has one simple source file like this:

file abc.c

void abcTest(int n){ 
    // I want store n as global variable
} 

To using this library in MyProject i have to create abc.h inside MyProject header folder:

file abc.h

#ifndef _ABC_H
#define _ABC_H 

void abcTest(int n);

#endif;

file MyProject.c(main file)

#include "abc.h"

void main(void) {
    abcTest(10);
}

Now, i want to store n as global variable, so, after a call to abcTest() i can retrieve the value of n whereever i want.

I'm developing a library with intention to reuse it in all my projects.

Was it helpful?

Solution

You'll need to declare the variable as external in all files you want to use his global value.

Example:

file abc.c

extern int global_a;
void abcTest(int n){ 
    global_a+=n;
} 

file abc.h

#ifndef _ABC_H
#define _ABC_H 

void abcTest(int n);

#endif;

file MyProject.c(main file)

#include "abc.h"
int global_a = 0; // always initialize global variables

void main(void) {
    abcTest(10);
}

Regards

OTHER TIPS

After compiling the MyProject.c, the abc.h file will be included in the translation unit, so a global static variable should remain visible within that translation unit. In order to access it from external objects you'll have to have a function in the translation unit that can pass the value to the outside.

Otherwise just name it anywhere in your file without scope, it will be global. In order to have a global carry across multiple files, use the extern keyword to tell the compiler that you're referring to a global variable already existent in another linker symbol.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top