-1

How do global variable declarations work?

For example:

In file1.c I am defining:

#define volt_add 0x20

uint8_t vol[8]= {0x53, 0x35, 0x05, 0x22, volt_add,0x00,0x00,0x00};

uint16_t EM_vol;

I need to use all above variables in file2.c.

I tried to define them in the global.h file and included that file in both file1.c and file2.c, but I am getting a multiple definition error, first defined here error.

How can I do it?

1 Answer 1

2

If you want global variable accessible from everywhere you include global.h, you'll need declaration of that variable in header (declatation only):

// globals.h:
extern uint8_t vol[8];

Anywhere else you'll #include "global.h"

But there must be one cpp or c file with:

#include "global.h"
uint8_t vol[8]= {0x53, 0x35, 0x05, 0x22, volt_add,0x00,0x00,0x00};

If you make this definition in header or more than one .c file, you'll get multiple definition error.

Another way would be make it static and make whole definition in the header, however each compilation unit will be using it's own instance and it won't be visible from other compilation units (compilation unit == every c file compiled into own .o file). This is issue on MCUs and if you even want to write into it, it'll be total mess (although nobody uses const correctness in C)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.