Do all C functions need to be declared in a header file - c

Do I need to declare all functions I use in a .c file in a header file, or can I just declare and define right there in the .c file? If so, does a definition in the .c file in this case count as the declaration also?

Do I need to declare all functions I use in a .c file in a header file,
or can I just declare and define right there in the .c file?
You used "use" in the first question and "define" in the next question. There is a difference.
void foo()
{
bar(10);
}
Here, foo is defined and bar is used. You should declare bar. If you don't declare bar, the compiler makes assumptions about its return type.
You can declare bar in the .c file or add the declaration in a .h file and #include the .h file in the .c file. Whether you use the first method or the second method is up to you. If you use the declaration in more than one .c file, it is better to put that in a .h file.
You can define foo without a declaration.
If so, does a definition in the .c file in this case count as the declaration also?
Every function definition counts as a declaration too.

For the compiler, it does not matter if a declaration occurs in a .h or a .c file, because the compiler sees the preprocessed form.
For the human developer reading and contributing to your code, it is much better (to avoid copy&pasting the same declaration twice) to put the declaration of any function used in more than one translation unit (i.e. .c file) in some #include-d header.
And you can define a function before using it.
BTW, you might even avoid declaring a function that you are calling (it defaults to returning int for legacy purposes), but this is poor taste and obsolete way of coding (and most compilers can emit a warning in that case).

No, it is not necessary.
The reason of the header files is to separate the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the .c file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.

The answer to both questions is yes. You can declare c-functions in both header and .c file. Same with definition. However, if you are defining it in header file, you may have slight problems during compilation.

By default functions have external linkage. It means that it is supposed that functions potentially will be used in several compilation units.
However sometimes some auxiliary functions that form implementations of other functions are not designed to be used in numerous compilation units. Such functions declared with keyword static have internal linkage.
Usually they are declared and defined inside some .c module and are not visible in other compilation units.

One occasion that requires functions to be declared in a separate header is when one is creating a library for other developers to use. Some libraries are distributed as closed source and they are provided to you as a library file (*.dll / *.so ...) and a header.
The header file would contain declarations of all publicly accessible functions and definitions of all publicly required structures, enums and datatypes etc.
Without this header file the 3rd party library user would not know how to interface with the library file and thus would not be able to link against it.
But for small, trivial C programs that are not intended for use by other people, no you can just dump everything into a C file and build it. Although you might curse yourself years later when you need to maintain that code :)

Related

Why should I declare a "private" function static when I can simply not put it in the header file?

I understand the static keyword is used for creating functions or variables which are "private" to the translation unit (the source file).
However, as far as I understand, in order to make sure a particular function or variable is not accessible from outside the .c file that it was declared in, I can simply not declare it in the corresponding .h file.
For example:
f.c
void public_func() {
// ...
}
void private_func() {
// ...
}
f.h
void public_func();
// no declaration of private_func
So why should I also declare private_func as static? Is that simply a convention or does it have a technical benefit over simply not declaring it in the .h file?
The problem is that compilers work on "translation unit" basis, meaning one .c file and all the .h files it includes. So it is traditionally not able to detect naming collisions across the whole project.
So if you don't make it static, the function has "external linkage" per default. Meaning if have a function private_func and another translation unit in the same project is using the same name, you get namespace collisions during linking and linker errors.
It is also a matter of correctness - private functions/variables should simply not be accessible from the outside, neither intentionally nor accidentally.
I understand the static keyword is used for creating functions or variables which are "private" to the translation unit (the source file).
That's true.
Is that simply a convention or does it have a technical benefit over simply not declaring it in the .h file?
There is a technical point here. Once compiler is done doing it's job it produces an object file. That file has a symbol table, which is later used by linker when the linker puts a program together from separate object files. static functions will not get into that table, so that direct references to that function from other object files will fail with "unresolved reference" error in the linking stage.
Benefits? Well you save some tiny space in you object file, linking stage will go faster, since there will be a smaller table to process. But that's tiny enough to not make a difference, unless we're talking about a made up case of thousands of functions with loooong names.
If you have a non-static function and you omit it's declaration in the header file, the function name still gets into a symbol table. And if I happen to know the declaration somehow (other than from the header) I can still call/reference the function directly from another translation unit, no linker error will happen.
Let's say you write a library that consists of several .c and .h files. The clients of your library will need to use some of the header files to use your library. They should only see the public functions.
But for the implementaiton of your library, you might also use header files so functions in your library can call other (internal) functions.
So you end up with two types of declarations:
For clients of your library
void public_func();
For internal use
static void private_func();
Preferrably, the private and public declarations are in separate header files and the clients of your library only need to include the header files with public functions.

Should a function prototype always be in its header file?

Lets say we have a few C source files such as file1.c, file2.c and main.c. We have functions as:
file1.c
|---> file1Func1()
|---> file1Func2()
file2.c
|---> file2Func1()
|---> file2Func2()
and the main file uses these functions. Now it would be natural that I create and add respective function prototype in header files file1.h and file2.h, then include these headers in main.c to use the functions.
What if I have a very large project with over thousand source (C) files, should I always create a header (then add function prototype) for every source file. Then include the header to use the functions?
Or using extern for using a function defined elsewhere (in some other source file) and rely on linker to search and fetch the function from the object file during link time?
Note: using the latter approach triggers MISRA warning of no function prototype.
All functions that are part of the interface, that is functions which is called by another module, should have function prototypes in the header file. Preferably together with comments documenting how that function should be used.
Functions that are not part of the interface and only used internally within the file should not have a prototype in the header. For such functions, declare the prototype at the top of the c file, and declare it as static.
This is how all (professional) C programs are written. As a side-note, this sound design is also required by MISRA-C.
There should never be a reason for you to use the extern keyword for functions. Note that a function prototype like
void func (void);
is completely equivalent to
extern void func (void);
If you need to use a function, include the relevant header.
What if I have a very large project with over thousand source (c) files, should I always create a header (then add function prototype) for every source file. Then include the header to use the functions?
The short answer is "Yes".
The slightly longer answer is "Yes but you may omit functions from header files that are implementation details of other functions in a source file".
Declaring functions in header files and #includeing the header files makes sure that function definitions and function calls stay in sync. Otherwise, it is easy to make mistakes and those mistakes are caught at link time instead of at compile time.
should I always create a header (then add function prototype) for
every source file.
The TL;DR; answer is Yes.
My personal opinion (and one that has been written into several company coding standards) is that each C Source file should have its own associated Header file to define the external interface.
Together, the C Source file and its associated Header file define the module - but only the Header file declares the interface.
All global objects (including function prototypes) should be declared in header file; I also advocate that the extern keyword should never(*) be used in a C Source file as this is (IMHO) breaking the declared interface for the module.
{*} OK, never is a strong word, and there may be exceptions... but they should be few and far between.

Is there a case when a C function can be defined within a header file?

Is there a case when a function can be defined within a header file? I was told by person whose opinion I respect that there are cases when a function can be defined in a header file included by multiple C source files. However, I could not find any. Just confirm, I define the function in-line in a header file but that also did not work. I will but have not found any answers yet. There is no practical requirement as such. I just wanted to see if there is some part of the C standard that I don't know of which will allow this. Thanks for any answers
Yes, but only if it is declared as static inline.
Functions that are declared simply as inline behave exactly like functions that are defined with no modifiers, except that they may be inlined within the translation unit that they're defined as inline in. They still have global scope, so including them in a header file will result in errors, as the function will be multiply defined.
static inline functions, on the other hand, do not have global scope — they only exist where they are used, more in line (ha ha) with the way you probably think of inline functions. As such, they're appropriate for use in header files.
No C function should not be defined in Header files.
function declaration can go in Header files.
But function definition should not ever go in header files.
Reason:
If function defination goes in header files then header will be included by multifple c files and when they are going to compile they will give error for multi defination of same files.
static inline function can be defined in Header files.
But that should not be used because
The "static" keyword in "static inline" is harmful in the situation
where a "static inline" function gets included and compiled in N
different files and does not get inlined. In this situation, one would
typically want the N copies of this function to get merged into one,
to avoid code bloat. But the "static" keyword prevents that, forcing
the linker to not merge these redundant functions.
As a side note to the answers/discussion on inline functions, I believe that theoretically one could define a function in a header in the same way as in a normal .c file, providing the header was only included once and in single location.
Though I'm not sure if the standard explicitly forbids this or not, it follows from the idea that the contents of a header file are essentially being copied and pasted into the top of the source file in which it is included from which point of view, there would be no issue.

C: Is it good practice to put static function prototypes in implementation files?

I am writing a C program and declaring all functions that are visible outside each compilation unit in the appropriate .h files. However, I also have some static functions in each compilation unit. I would prefer not to have to order the static functions in a particular way. Should I declare all of the static functions in header files, or just put all of the static declarations at the top of each implementation file?
Header files should be a sort of "menu" that tells other source files what functions, types, etc. are exported by your module. Whenever possible, you shouldn't leak any information about the internal implementations in the header file, since it makes the code harder to modify (if a client of your header tries to use a function that you later remove) and harder to use (because the reader has to sift through private function prototypes to find the actually exported functions).
Accordingly, it's best to put prototypes for functions that are private to one source file at the top of that source file rather than in the corresponding header file.
Hope this helps!
In case you need these static functions in more compilation units, place their declarations into the header file, which is included by all files, where you need this functions. Don't copy-paste them to other .c files (Don't Repeat Yourself).
If there's a function, which is used only within a single compilation unit, there's nothing wrong with it being declared and defined in the same .c file. Actually it's even better since you're not exposing what is not meant to be exposed.

Where should non-interface function prototypes be placed?

I've read repeatedly that header files should include all the declarations that other files will need to use the source code. Suppose then that you have a function that is not used directly by other source files (a non-interface function, in other words). Should its prototype be placed at the top of the .c file, since it will not be used by other files? Or should it be placed in the header files with all the other functions, in order to fully summarize the functions present in the .c file in one place?
The header contains the interface information (whatever is needed for the outside world to use the functionality in the "module" -- e.g. the .c file). So internal functions (that are not used from outside), do not go into the header
In the .c file it depends on organization
some people like to list all internal function declaration at the top, so they are in one place.
others rely on ordering so a function is defined by the time it is used (in another function); and only forward declare it if necessary (e.g. recursive functions that call each other)
If the function is not used by other .c files, it should not have a prototype in a header file. You should give it the static modifiler, and place
the prototype at the top of the (only) .c file where it is used.
If it's reasonable and possible, you can just define the function before all the
functions that call it, so you don't even need a prototype.
Yes, the prototype of a private function should be placed in the same .c file as the function. The header defines the external interface.
Rather than forward declarations, some programmers prefer to define the functions in the order they're used so prototypes are unnecessary. Of course, you can't do this if two or more functions call each other.
My personal preference is to declare all of the functions first, so you'll have an overview of the file.
If you have functions that are used within a single module (a small set of files that together implement a functional unit), it's perfectly reasonable to create a second module-specific header file. All of the files in the module—but no external source files—will #include it.
Given that header files are essentially the only way to declare an external interface in C, things not part of that interface should not be in the header file.
C being what it is, sometimes this is not practical, because the internal view of an externally visible definition needs to refer to it; in this case you might place it in the header but protected by a #define that clearly indicates its internal provenance, and likewise use #ifdef to select the internal vs. external version of the definition that requires it. (You will see this in system header files often.) It's better to try to avoid this, though.
Putting at all the function declarations in the prototype syntax at the top of the .c source file is good style in my opinion. It serves also to document you source code for the reader.
You don't want to put the declarations in the .h header file as you would unnecessarily expose the internals of your programs.
Oh, and don't forget to add the static specifier in the function declarations.

Resources