Pololu Robotics & Electronics
Menu
My account Comments or questions? About Pololu Contact Ordering information Distributors

Pololu Forum

C compiler extern oddity


#1

to try and keep my project tidy I have several C source files
variables are declared in one and used in the others
all fine and dandy,
except…

one.c const uint8 BusyPin=14;

two.c extern uint8 BusyPin;

ok
what do you think the value of BusyPin is in one.c?
what do you think the value of BusyPin is in two.c?

I know what I expected
but I got 14 in one.c
and 0 in two.c
no errors reported, but the software was as confused as hell!

what do the committee think?

a) bug
b) stupid programmer should have known better

the fix, as I now know is

two.c extern const uint8 BusyPin;


#2

Hello, mmcp42.

I’m going to go with option B. :smiley:

You should put all of your extern statements in to a header file that you #include in every C file that uses the variables, even the file where the variables get defined:

vars.h:

one.c:

#include "vars.h" const uint8 BusyBin = 14;

two.c:

#include "vars.h" ...

Had you done this, the compiler would have been able to detect the inconsistency in the declaration and the definition, and you would have gotten an error like this:

one.c:2: error 91: extern definition for 'BusyPin' mismatches with declaration.
vars.h:1: error 177: previously defined here

Also, your code will be more efficient if you use #defines instead of consts, because the consts actually get stored in flash and have to be read at run time.

#define BusyPin 14

–David


#3

did as you suggested
#include "MySoftly.h"
with everything defined there
managed to clear up one or two anomalies along the way :smiley:
cheers