-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.
Global statics are. Local statics are local to their block (typically a function).
- Static variables also can stay around after the function is exited.
Correct. This applies specifically for local statics, because global varaibles both static and external always have this property.
-A variable declared outside of Main is global
Outside of any function.
- and a .c file
other than the file the global is declared in...
- that wants to use it must extern it.
Correct.
-
-Static functions are visible to the .c file. My problem here is why
-declare them static? Isn't static assumed?
Nope. Actually extern is the default for all global entities. So if you don't want outsiders to the file to use global functions/variables you must attach the static tag.
-A function can be called by other .c files if its prototype is
-External.
Yes, which again is the default.
-
-I have read that it is good C practice to code prototypes for each
-function.
Absolutely. Want an example? try this:
-------- file1.c --------------- main() { f1(3); }
--------------------------------
--------file2.c----------------- #include
void f1(double val,int junk1,int junk2) { printf("val = %f junk1 = %d, junk2 = %d\n",val,junk1,junk2); }
--------------------------------
Compile and link together. Fails miserably but still runs. A big mess. However if you include the prototype in file 1:
-------- file1.c --------------- void f1(double val,int junk1,int junk2);
main() { f1(3); }
--------------------------------
It magically generates an error because the prototype gives the compiler enough info to know that the call is incorrect. Also if f1 had the correct number of parameters, the int to double conversion of the 1st parameter also automagically happes because of the prototype.
Definitely prototype before you use. I wish there was a way to force the compiler to require prototypes before use.
- Should I code the prototypes in a .h file associated with
-the .c file?
There are different ways of doing it. It depends on usage. Generally I'll dump all of the prototypes into a single project .h file then include it into all the source files. However if it's a bit of code, like a hash table for example, that has multiple uses in multiple projects, then I'll give it its own header file.
There isn't necessarily one perfect has to do it. But there is no doubt that it needs to be implemented somehow.
- Where do I extern the prototype if I plan to use the
-function in multiple .c files ?
See above.
BAJ