Morris Keesan
4/21/2011 2:39:00 AM
On Wed, 20 Apr 2011 19:18:33 -0400, Keith Thompson <kst-u@mib.org> wrote:
> pozz <pozzugno@gmail.com> writes:
>> Many times I need to define a long list of variables in a C code and use
>> it in several other modules.
>>
>> For example, I have a C file with constant strings used in the overall
>> program:
>> --- strings.c ---
>> const char msg1[] = "Please, wait";
>> const char msg2[] = "Enter the password";
>> const char msg3[] = "Password isn't correct";
>> ...
>> ---
>>
>> Of course I need a corresponding include file:
>> --- strings.h ---
>> extern const char *msg1[];
>> extern const char *msg2[];
>> extern const char *msg3[];
>> ---
>
> This is wrong. You define msg1 as an array of char, then declare it as
> an array of pointers to char.
>
> Note that either
> extern const char *msg1;
> or
> extern const char msg1[];
There appears to be a the end of a sentence missing here, but it's
important to note here that "extern const char *msg1;" is totally
incompatible with the definition "const char msg1[] = "Please, wait";
> If you want to make an array object visible in a .h file, you also need
> to make its size visible, and therefore fixed -- but that defeats the
> purpose of defining the content in a .c file.
Well, no, you don't, and no, it doesn't. It's perfectly legal to
define msg1 as above:
const char msg1[] = "Please, wait";
in a .c file, and have an extern declaration in a .h file that says
extern const char msg1[];
as long as the code which only sees the extern declaration doesn't try
to apply the sizeof operator to msg1.
> Probably your best bet is:
>
> --- strings.h ---
> extern const char *msg1;
>
> --- strings.c ---
> const char *msg1 = "Please wait";
I respectfully disagree. One thing that I do consider important is to
#include "strings.h" in strings.c. This won't keep you from having
items declared in one file or another that are missing from the other,
but it will make sure that the compiler will catch the error if the
declarations in the two files are not compatible, e.g. if the definition
declares msg1 as an array while the extern declaration declares it as
a (char *).
--
Morris Keesan -- mkeesan@post.harvard.edu