Using the extern keyword incorrectly

Thread Starter

jjj059

Joined Aug 1, 2008
9
I have a C project where a global variable is defined as a 16-bit unsigned integer. This variable is used in a file separately from where it is defined. This other file identifies the global variable using the extern keyword, but has the datatype (incorrectly) as a 16-bit signed integer.

So what will happen here? Will the file using the 'extern' version of the variable compile thinking it is signed? Or will the compiler see the global definition and recognize that it is unsigned?

There were no compile or link warnings about this mismatch.

Obviously I will fix this (someone else's mistake, not mine), but I was curious about how the code would actually run. This code is destined for an embedded 32-bit Motorola chip.
 

spinnaker

Joined Oct 29, 2009
7,830
My guess in the file where it is defined it will treat it like an unsigned. In the file where it is extern it will treat it as signed.
 

Papabravo

Joined Feb 24, 2006
21,159
More to the point is that extern should not be in a .C file it should be in one and only one place in a .H file

You could also have a MACRO that expands as a data definition in a .C file and an extern statement in a .H file -- An elegant solution
 

Thread Starter

jjj059

Joined Aug 1, 2008
9
One thing that I didn't mention was that the file that is using the extern is auto-generated C-code. So, after digging into it a bit, I discovered the function using the extern variable is expecting signed, so it treats it as signed. I tested the code and this was the case. I guess maybe there's a point between the compile and link steps where the data type information is gone and the visibility across files to catch this type of error suddenly appears?

Indeed, the extern statement was in a .h file.

Papabravo, I'm not sure what you mean by having a MACRO. I'll have to google this, but feel free to elaborate.

Thanks.
 

stahta01

Joined Jun 9, 2011
133
Old school (K&R C days) was to define EXTERN as extern or as an empty string when an macro was defined. The macro was only defined in a single C file, normally the one containing the main function.

Tim S
 

spinnaker

Joined Oct 29, 2009
7,830
Old school (K&R C days) was to define EXTERN as extern or as an empty string when an macro was defined. The macro was only defined in a single C file, normally the one containing the main function.

Tim S

I think I get it. Sort of like EXPORT and IMPORT for DCOM objects?
 

Papabravo

Joined Feb 24, 2006
21,159
In my case I used the word GLOBAL which expanded as a null string or as 'extern' so that
Rich (BB code):
GLOBAL unsigned char *p ;

would expand as either

unsigned char *p ;    // define p as pointer to unsigned char

or

extern unsigned char *p ;  // define external linkage to p
This tended to highlight that fact that a global variable was being defined or referenced.
 
Last edited:
Top