C help please - C newbie

Do you have a question? Post it now! No Registration Necessary

Translate This Thread From English to

Threaded View
Hi, I am an Assembly language programmer of 12 years, now starting to
code in C. I am still a C newbie and have some confusion.

I am finding that I am getting bogged down with uses of static /
extern for functions and variables. I am also getting a bit confused
with function prototyping and header files. I have searched the
internet quite a bit but I am still confused.

I think that I know the following;  (Please clarify)

Static variables are local to the .c file.  Static variables also can
stay around after the function is exited.
A variable declared outside of Main is global and a .c file that wants
to use it must extern it.

Static functions are visible to the .c file.  My problem here is why
declare them static?  Isn't static assumed?
A function can be called by other .c files if its prototype is
External.

I have read that it is good C practice to code prototypes for each
function.  Should I code the prototypes in a .h file associated with
the .c file?  Where do I extern the prototype if I plan to use the
function in multiple .c files ?

Any help / suggestions would be greatly appreciated.

thank you

Bradley

Re: C help please - C newbie
snipped-for-privacy@canoemail.com (Bradley) wrote in

Quoted text here. Click to load it

Yes, but you want to restrict scope of all functions but those that
external files require to use your .c file.

Quoted text here. Click to load it

No, if it is not declared static. The prototype is needed to tell the
compiler what the function signature looks like.

Quoted text here. Click to load it

It is good practice but only put functions, constants, etc. in a header
file for general consumption if they are needed in files other than your
main .c file. That is, leave your static functions in your .c file along
with "private" file scoped variables and manifest constants.

Also, here's a response I gave to a person in comp.lang.c, I hope it
helps.

If foo() preceeded main() in the file you got the prototype from the
definition. E.g.

static int foo(void) /* definition and prototype in one */
{
    return 0;
}

/* Since foo() is above main(), C already has foo's prototype.
*/
int main(void)
{
    return foo();
}

Quoted text here. Click to load it

A simplistic view can be used if not too picky: "static means the static
thing has duration for the life of the program and is restricted in scope
to the nearest enclosing brace or translation unit." My words, not the
spec. So using my smushy definition, you can say that a static function
will exist for the life of the program and be visible (scoped) to only the
file that contains it. Similarly,

int foo(void)
{
    static int butter;

    return ++butter;
}

int main(void)
{
    foo();
    return 0;
}

butter will exist for the life of the program and be visible only within
foo() since foo's opening brace the nearest enclosing brace.

Quoted text here. Click to load it

The question is the otherway round, why make a function visible outside a
module? Answer, because it is absolutlely essential to using the module.
Many functions to work within a module but have not externally usable
benefit.

Try to think about a module and what interfaces into it you feel are the
minimal ones you should provide to consumers of the module and make only
those functions non-static and then prototype them in the module's
accompanying header file.

Example disk.c:

static unsigned char readRegister(int regOffset)
{
    unsigned char regValue;

    regValue = /* some system specific stuff */;

    return regValue;
}

static void writeRegister(unsigned char regValue, int regOffset)
{
    /* some system specific stuff */ = regValue;
}


int dsk_readSector(void *pBuf, size_t bufSize, unsigned long sectorLba)
{
    writeRegister(sectorLba, LBA_OFFSET);
    writeRegister(WRITE_PIO, CMD_OFFSET);
    dma_configRead(pBuf, bufSize);
    
    return !(readRegister(STATUS_OFFSET) & ERR);
}

So here I, the consumer disk.c, care only about reading a sector, I don't
care how disk.c does this. I care only about reading. Thus, as the
implementer I hide read/writeRegister() in the file and expose only
dsk_readSector() in disk.h for external consumers. Also, as the
implementer, I keep consumers away from the disk registers by not
publishing a means to screw with them (this is good).

Does this make sense now?

--
- Mark ->
--

Re: C help please - C newbie

Quoted text here. Click to load it

No! I'm thinking assy. now. Functions have static duration but not static
scope by default. You *must* add static to them to reduce their scope to
the current translation unit.

--
- Mark ->
--

Re: C help please - C newbie
Quoted text here. Click to load it
You mean linkage?
static when used on a finction is different to static applied to a
variable.

Quoted text here. Click to load it

This is good practice.

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England    /\/\/\/\/\
/\/\/ snipped-for-privacy@phaedsys.org       www.phaedsys.org \/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

Re: C help please - C newbie

Quoted text here. Click to load it

I was thinking assy. where things are "private" by default (aren't they)?
As for static on a function vs. variable are they really that different?
Static on a variable means it duration is program but doens't exclude
reducing it scope to the current file. Likewise, static on a function
means scope to file but doesn't exclude meaning program duration.

--
- Mark ->
--

Re: C help please - C newbie


get a copy of K&Rs The C Programming Language.  do all the exercises.  many
people agree that though the book was written in the seventies, it's still
the best book for students and professional reference.

Quoted text here. Click to load it

static variables have file level scope and typically presist throughout
operation.

Quoted text here. Click to load it

all vaiables that are decleared outside of any functions are going to have
external linkage or static (i,e,. not auto).

Quoted text here. Click to load it

no, the default is non-static and externally accessable to other c files.

Quoted text here. Click to load it

correct.


yes.

Where do I extern the prototype if I plan to use the
Quoted text here. Click to load it

extern is assumed.

get the book.

-bryan

Quoted text here. Click to load it



Re: C help please - C newbie

Quoted text here. Click to load it

Why typically? I believe the *must* persist for the duration of the
program.

--
- Mark ->
--

Re: C help please - C newbie


you're right mark, what i wrote isn't proper for a standard c context and
was misleading.

however, once a data range is fixed in the image you can do whatever you
like with it.  as i'm sure you're well aware that "static" is only enforced
by the c compiler and or linker.

again sorry for the confusion.

-bryan

Quoted text here. Click to load it



Re: C help please - C newbie

Quoted text here. Click to load it


Not if the compiler can determine that they're no longer needed after
some point in program flow.  They must behave *as if* they persisted
for the duration of the program --- but if the program doesn't look,
the compiler is allowed to re-use the space otherwise.

--
Hans-Bernhard Broeker ( snipped-for-privacy@physik.rwth-aachen.de)
Even if all the snow were burnt, ashes would remain.

Re: C help please - C newbie

Quoted text here. Click to load it

I'd like to know if you have an example of such a condition as I'm having
a hard time seeing how a compiler could know that it will swap out a
function for use by another. Maybe I'm too used to Harvard architectures.

--
- Mark ->
--

Re: C help please - C newbie
Quoted text here. Click to load it

Observe.

static int switch = 0;
static int x;
static int y;

void test(void){
  if (switch == 0) {
    do a whole bunch of stuff with x
    if (some interesting case) {
      switch = 1;
    }
    do a bunch of stuff with y;
  } else {
    do a bunch of other stuff with y;
  }
}

Observe that the switch initially points to x, and the program uses x.  Once
the switch is thrown to y, the program only uses y, and NEVER AGAIN TOUCHES
X.  A sufficiently-advanced compiler could, in principle, notice that x and
y have disjoint lifetimes, and use the same storage location for the two
variables.



Re: C help please - C newbie

Quoted text here. Click to load it

First, you can't have a variable names 'switch' since this is a keyword.
Second, I was asking about static not not having program duration for a
function, not a variable.

Thanks.

--
- Mark ->
--

Re: C help please - C newbie

Quoted text here. Click to load it


We were talking about variables, not functions.  But since you mention
it: code banking / overlaying works by essentially the same "as if"
rule.  From the abstract point of view of the compiled code, it looks
as if all functions were available at all times, when in fact they're
not.

But a compiler like Keil's C51, which already does static call tree
analysis anyway, could reasonably easily discover that function foo()
was only ever called a couple of times early on, and then never again.
Now, if there's a static-duration variable "bar" that's used only by
foo(), and another static-duration variable "bletch" that is not used
at all before the final call of foo() has terminated, then "bar" and
"bletch" _can_ be put in the same memory position, because there's no
way the code could know about this.

Whether or not a compiler actually attempts to exploit this
possibility is mainly a question of motivation.  It's absolutely
allowed by the language definition, but may not be applicable
frequently enough in real-world code to be worth the bother.  Clever
programmers may even find this optimization on their own, if pressed
for space.

The "as if" rule is simple: as long as the program behaves the same
way (in all aspects that the standard defines) _as if_ the
optimization hadn't taken place, the optimization is allowed.

Quoted text here. Click to load it

The architecture does not influence this much, if at all.

--
Hans-Bernhard Broeker ( snipped-for-privacy@physik.rwth-aachen.de)
Even if all the snow were burnt, ashes would remain.

Re: C help please - C newbie
Quoted text here. Click to load it

Do NOT get a copy of K&R

Quoted text here. Click to load it
Do NOT do the exercises

Quoted text here. Click to load it

Not it is NOT. K&R was written for desktop/ Unix programmers in 1978

K&R SECOND edition was in 1988 the year before the ANSI C standard (C90)
and two years before the ISO C standard C90.

Most embedded compilers adhear to C90+ the TC's and Amendment A1....
Effectively C95.

So K&R is well out of date. There are many better books available for C
programmers doing embedded work.  What sort of targets are you looking
at?

See the book reviews at
www.accu.org

This is a C programmers web site with reviews of over 3000 books.  NB
the ACCU does not sell books

Regards
        Chris

PS, just for the record I do have a copy of K&R (2nd ed) but I would not
use it to learn from.

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England    /\/\/\/\/\
/\/\/ snipped-for-privacy@phaedsys.org       www.phaedsys.org \/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

Re: C help please - C newbie


chris,

i can respectfully acknowledge you're point of view.  however, i and many
others believe the k&r book is still valid for learning simply because all
the concepts are plainly stated and explained. it is an easily and quickly
digestible text.

also, i will remind you that off all the c code out there a relatively small
percentage of it adheres to C90+.

-bryan

Quoted text here. Click to load it
still



Re: C help please - C newbie

Quoted text here. Click to load it
small

These things are all a matter of opinion, of course, so here's mine...

The original K&R book was written in the seventies, when C was new.
However, we are no longer living in the seventies, and C has changed a great
deal in the last 30 years.  Obviously it is still lumbered with many of the
design decisions that don't fit with modern language design (for example,
the idiotic idea that everything at file scope has global linkage unless it
is explicitly declared static, or the joys of "break" in switch statements),
but a great deal has changed for the better.

The O/P wants to learn to *write* C code.  He should learn to make the best
of C as it stands *today*, in popular compilers *today*, and if it turns out
that one day he has to write code for an ancient non-ANSI C compiler, then
he can deal with it at that time.  In the meantime, he should be writing C
code that is as solid and readable as possible - all functions should be
prototyped, using // comments, static inline functions, consts and enums
instead of #defines, and so on.

The K&R book may be a great teaching book - it is a long time since I read
it, so I can't remember - and it may be better in that sense than some
modern text trying to teach you everything in 24 hours or 21 days or
whatever.  The trouble is, it would be teaching him the wrong thing.

David


Quoted text here. Click to load it



Re: C help please - C newbie
Quoted text here. Click to load it


Most adheres to C90+  Some now almost C99.  Certainly all the compilers
are somewhere between C95 and C99.  Many of the things in K&R are not
permitted in many coding standards etc.

There are also many better books for learning C especially fro some one
coming from an assembly background  to embedded c.

I have seen the effect of a K&R taught programmer coming to grips with
an embedded project... wanted to use sdterr and printf to hard disk for
debugging on an 8-bit smart card....

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England    /\/\/\/\/\
/\/\/ snipped-for-privacy@phaedsys.org       www.phaedsys.org \/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

Re: C help please - C newbie


sorry, i seldom see standard c programs that do any real work.  most are
full of platform specific types, inline compiler, link, or source control
commands, inline assembler, etc.

also, many c compilers have an option to allow k&r syntax.

in a perfect world, all c code would conform to the latest ISO.

actually, in a perfect world we probably would not be writing programs in c.
:)

however, you do make a good point that the k&r book is probably not a good
transition text from assembler languages to c.  the authors of the book
disliked assembler and actually developed c so that they wouldn't have to
use their assemblers.

-bryan


Quoted text here. Click to load it
all
quickly
small



Re: C help please - C newbie
Quoted text here. Click to load it

Exactly.  This is why a standard is not the best thing to learn a
language from.

Quoted text here. Click to load it

Not these days. Remember K&R 1st ed is 30 years old and K&R 2nd ed is
C90

Quoted text here. Click to load it
assuming C99 is perfect (opening another can of worms in his asbestos
suit)

Quoted text here. Click to load it
FORTH!
There, I've said it before one of the Priests of old FORTH  (poof :-)
says it...

Quoted text here. Click to load it


/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\ Chris Hills  Staffs  England    /\/\/\/\/\
/\/\/ snipped-for-privacy@phaedsys.org       www.phaedsys.org \/\/
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/

Re: C help please - C newbie

Quoted text here. Click to load it

I'll hold my hand up for the new Forth, not the old FORTH.
Optimised ANS Forths. As fast as C, wth a wonderful test and
debug environment.

Honest, I did think before responding.

Stephen
--
Stephen Pelc, snipped-for-privacy@INVALID.mpeltd.demon.co.uk
MicroProcessor Engineering Ltd - More Real, Less Time
We've slightly trimmed the long signature. Click to see the full one.

Site Timeline