2

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?

Tim
  • 3,755
  • 3
  • 36
  • 57
  • What are you doing that you want things that look like strings but aren't null-terminated, and you also want to obtain the length of said not-strings with `sizeof` rather than `strlen`?!?! –  Jun 10 '15 at 02:21
  • @Hurkyl yes, i could use that strlen – Tim Jun 10 '15 at 02:35
  • 1
    At the very least, you need to read [How do I use `extern` to share variables between source files in C?](http://stackoverflow.com/questions/1433204) Most particularly, you cannot reliably initialize the variables in the header — not simply. If you do, the header can only be used by one source file in your program. Using `char *` instead of arrays simply wastes space storing the pointers. And it doesn't lose the terminating null byte. – Jonathan Leffler Jun 10 '15 at 03:45

1 Answers1

6

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[];
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • thanks! so it is a bad idea to define my global variable in a header and included in multi C files? – Tim Jun 10 '15 at 02:36
  • i tried it before i dont get any error linking, but if i would use const char *AT_DEVICE_SECURITY = "ATDS"; i would get error linking, – Tim Jun 10 '15 at 02:45
  • @Tim: you may just be getting lucky. The standard requires a single definition; including the header in more than one source file gives multiple definitions. A linker might be prepared to overlook that — but it is unlikely. Which platform are you on? Which compiler and linker are you using? – Jonathan Leffler Jun 10 '15 at 03:47
  • @JonathanLeffler i am using IAR linker for stm32, this code is mainly for embedded system, alright i will change the way i decalre my varibale! thnks! :) – Tim Jun 10 '15 at 03:56