Declaring global char array in C header file

12.8k views Asked by At

I have a header file that contains all the string command as shown below:

const char AT_RSSI[] = "ATRSSI\r\n";
const char AT_DEVICE_SECURITY[] = "ATDS";

But, using this method each of char sentence is appended with \0 at the end and this is inconvenient as I need to remove 1 char, each time I use the sizeof() method

There is another solution is to use

//header file
extern const char *AT_RSSI;

//some.c
const char *AT_RSSI = "ATRSSI\r\n";

and declare it in one of the .c file, but I do not like this approach. I want all my constant variable to be declared in the header file

May I know how can I declare a constant global variable char array that can be included in various .c file?

1

There are 1 answers

4
Yu Hao On BEST ANSWER

The problem of the first piece of code is, you are putting definitions in a header file, which would lead to multiple definition error if the header file is included by multiple .c files.

In general, put definitions only in a .c file, and put their declarations in a header.

That means, put this in a .c file:

const char AT_DEVICE_SECURITY[] = "ATDS";

and this in the header:

extern const char AT_DEVICE_SECURITY[];