What do .c and .h file extensions mean to C? - c

It's all in the title; super-simple I reckon, but it's so hard to search for syntactical things anywhere.
These are two library files that I'm copying from CS50.net, and I'm wondering why they have two different extensions.

.c : c file (where the real action is, in general)
.h : header file (to be included with a preprocessor #include directive). Contains stuff that is normally deemed to be shared with other parts of your code, like function prototypes, #define'd stuff, extern declaration for global variables (oh, the horror) and the like.
Technically, you could put everything in a single file. A whole C program. million of lines. But we humans tend to organize things. So you create different C files, each one containing particular functions. That's all nice and clean. Then suddenly you realize that a declaration you have into a given C file should exist also in another C file. So you would duplicate them. The best is therefore to extract the declaration and put it into a common file, which is the .h
For example, in the cs50.h you find what are called "forward declarations" of your functions.
A forward declaration is a quick way to tell the compiler how a function should be called (e.g. what input params) and what it returns, so it can perform proper checking (for example if you call a function with the wrong number of parameters, it will complain).
Another example. Suppose you write a .c file containing a function performing regular expression matching. You want your function to accept the regular expression, the string to match, and a parameter that tells if the comparison has to be case insensitive.
in the .c you will therefore put
bool matches(string regexp, string s, int flags) { the code }
Now, assume you want to pass the following flags:
0: if the search is case sensitive
1: if the search is case insensitive
And you want to keep yourself open to new flags, so you did not put a boolean.
playing with numbers is hard, so you define useful names for these flags
#define MATCH_CASE_SENSITIVE 0
#define MATCH_CASE_INSENSITIVE 1
This info goes into the .h, because if any program wants to use these labels, it has no way of knowing them unless you include the info. Of course you can put them in the .c, but then you would have to include the .c code (whole!) which is a waste of time and a source of trouble.

Of course, there is nothing that says the extension of a header file must be .h and the extension of a C source file must be .c. These are useful conventions.
E:\Temp> type my.interface
#ifndef MY_INTERFACE_INCLUDED
#define MYBUFFERSIZE 8
#define MY_INTERFACE_INCLUDED
#endif
E:\Temp> type my.source
#include <stdio.h>
#include "my.interface"
int main(void) {
char x[MYBUFFERSIZE] = {0};
x[0] = 'a';
puts(x);
return 0;
}
E:\Temp> gcc -x c my.source -o my.exe
E:\Temp> my
a

They're not really library files. They're just source files. Like Stefano said, the .c file is the C source file which actually uses/defines the actual source of what it merely outlined in the .h file, the header file. The header file usually outlines all of the function prototypes and structures that will be used in the actual source file. Think of it like a reference/appendix. This is evident upon looking at the header file, as you will see :) So then when you want to use something that was written in these source files, you #include the header file, which contains the information that the compiler will need to know.

The .c is the source file and .h is the header file.

The .c files are source files which will be compiled. The .h files are used to expose the API of a program to either other part of that program or other program is you are creating a library.
For example, the program PizzaDelivery could have 1 .c file with the main program, and 1 .c file with utility functions. Now, for the main part of the program to be able to use the utility functions, you need to expose the API, via function prototype, into a .h file, this .h file being included by the main .c file.

.c : 'C' source code
.h : Header file
Usually, the .c files contain the implementation, and .h files contain the "interface" of an implementation.

Related

When to use #include "file.c" and when to use #include "file.h" in c

In what situations we need to use .h file and when to use the .c file in C.
Are they two alternatives for a same purpose?.
Please explain.
Never include .c files
If you include something, it should be a .h file.
Code goes into code files, .c.
Headers, .h files, contain only what can be compiled more than once, i.e. declarations, macro definitions, more includes.
If necessary, headers use reinclusion guards.
Whenever you feel tempted to include a .c file, you instead want to add it to your project so that it gets processed during building, i.e. gets compiled by its own and in a further build step gets linked into the created binary.

C - Using .h files

I'm in the process of learning C for a coursework assignment. One thing that confuses me is header files. I've tried to find some information regarding my question to no avail.
My question is, say I have 3 different .c files. The convention is (atleast from reading sources) - each .c file has it's own .h file, e.g. parser.c has parser.h, lexer.c has lexer.h, typechecker.c has typechecker.h (if we were making a compiler).
We then go on to add a statement:
#include "parser.h"
#include "typechecker.h"
in the lexer.c file, and do the same with the other .c files (changing the header files we include).
Instead of using that convention, is it okay to add all the prototypes for all 3 classes files into one header, say header.h, and just include that in all 3 classes? The problem with this is that the 3 classes will have prototypes of functions already included in this class, but I don't see this as a problem (I'm a beginner at C so I could be wrong).
Thanks.
what you suggest is permissible but not recommended. Having all prototypes in one header will cost you in terms of compilation and building. try to concentrate on "why header files are used?". if you get this answer you will refrain from adding everything in one header file. header files are meant for modularity to provide source files only those information which they need. Secondly in large projects you have to define "private" header files which are used internally by your code and are not visible to outer word. Ofcourse you will provide other users with header file in order to use your code.
So It is not advisable to put all prototypes even in your start of learning. As starter, make one header file per source file.
EDIT
if your header1.h has function function1(), wherever(all source files) you use function1(), you will add header1.h

Including source files in C files

I am very new to C, so I apologize for this newby question.
I would like to use this source code in my project: http://base64.sourceforge.net/b64.c.
So, I include it in my test file:
#include <stdio.h>
#include "b64.c"
int main()
{
return 0;
}
However, main() is defined in b64.c as well, so upon compiling, I get:
test.c:4:5: error: redefinition of ‘main’
b64.c:495:5: note: previous definition of ‘main’ was here
test.c: In function ‘main’:
test.c:5:1: error: number of arguments doesn’t match prototype
b64.c:495:5: error: prototype declaration
What is the correct usage of this source file, or any? How do we correctly use it, or use functions defined in that file?
Edit: I understand that the problem is due to the duplicate definitions of main. I know there can only be one. My question is rather, won't every meaningful project need it's main method? Then why is there a main method defined in b64.c? Are we just supposed to delete this method from the source code? It seems odd that the source code doesn't just come ready to be included and used.
It is never a good idea to #include a C source file into your code. You can either copy the code from the other C source file into your code, or include the needed prototypes in your code and make a call to the functions, linking those after compiling them separately.
you should use one of the two main functions.
If you want a new main, write your main method in your file and remove it from the 'b64.c' file, if you want to use it from the 'b64.c' file remove your (empty) main.
If main is defined in b64.c either you cannot simply redefine it in your main source file.
What do you want is to use several functions from b64.c in your program. Delete the main function from it and create a header file where you protoype all of the functions in b64.c. After that, include this header file in your main program. Have a look at this short Wikipedia entry. It should give you an overview of the topic.
Besides this: It seems that you aren't very familar with C. Try out some tutorials and go on reading about C.
First of all, you must redeclare the .c file as a .h, and then you have to go through the source code and rename any duplicate methods or global variable names. The main method is the starting point of a program so there can only be one.
(Usualy you dont include .c files, only .h)
if you want the functions inside the "b64.c" you should delete the main function from "b54.c"!
A C application needs one main() function. Your file b64.c looks like a self-sufficient C program so you don't need your test.c. Just compile and run b64.c.
When you are including that source file you are getting 2 main() declaration which is incorrect. So you have redefined "main" in this case.
Including .c into another .c file doesn't make sense. C files compile to .obj files, which are linked by the linker into the executable code , so there is no need to include one .C file into another. Instead, you can make a .h file that lists the functions and include that .h file

How to use a function from an object file

I'm pretty sure this question is a duplicate, but can't find an answer.
I wrote a function (in "function.h" and "function.c" files), and compiled it to "function.o" file. I want to use the function defined in "function.c" in my main source, but without including "function.h". Is that possible, to compile main.c using just "function.o"?
A header file is (usually) just a list of declarations which are inserted textually (by #include) into your source files.
Therefore, if function.h contains
void foo(int x);
and you have #include "function.h" in your main source file, it is exactly equivalent to just writing void foo(int x); in your source file.
Header files are useful for code organization because it would be highly inefficient (and error-prone) to copy those declarations by hand into every source file that used them. But, if you want to avoid the header file for any reason, copying those declarations directly into your source file has the same effect as #include'ing the file.

Include c file in another

I want to include a .c file in another. Is it possible right? It works well if I include a header file in a .c file, but doesn't work as well if I include a .c file in another .c file.
I am using Visual Studio and I get the following error:
main.obj : error LNK2005: _sayHello already defined in sayHello.obj
/* main.c */
#include "sayHello.c"
int main()
{
return 0;
}
/* sayHello.c */
#include <stdio.h>
void sayHello()
{
printf("Hello World");
}
I don't know what this error could mean. Time to ask more advanced C coders. :)
I want to include a .c file in another.
No you don't. You really, really don't. Don't take any steps down this path; it only ends in pain and misery. This is bad practice even for trivial programs such as your example, much less for programs of any real complexity. A trivial, one-line change in one file will require you to rebuild both that file and anything that includes it, which is a waste of time. You lose the ability to control access to data and functions; everything in the included .c file is visible to the including file, even functions and file scope variables declared static. If you wind up including a .c file that includes another .c file that includes another .c file und so weiter, you could possibly wind up with a translation unit too large for the compiler to handle.
Separate compilation and linking is an unequivocal Good Thing. The only files you should include in your .c files are header files that describe an interface (type definitions, function prototype declarations, macro defintions, external declarations), not an implementation.
It works, but you need to be careful with how you build the program. Also, as folks have pointed out in comments, it's generally considered a bad idea. It's unexpected, and it creates problems like these. There are few benetfits, especially for what seems like a trivial program. You should probably re-think this approach, altogether.
After doing something like this, you should only compile main.c, and not attempt to link it with the result of compiling sayHello.c, which you seem to be doing.
You might need to tell Visual Studio to exclude the latter file from the build.
Yes, any '.c' file can be included into another program.
As one include '.h' file like 'stdio.h' in the program.
After that we can call those function written into this external file.
test.c::
#include<stdio.h>
#include<conio.h>
void xprint()
{
printf("Hello World!");
}
main.c::
#include "test.c"
void main()
{
xprint();
getch();
}
Output:: Hello World!
This is a linker error. After compiling all your .c files to .obj files (done by the compiler) the linker "merges" them together to make your dll/exe. The linker has found that two objects declare the same function (which is obviously not allowed). In this case you would want the linker to only process main.obj and not sayhello.obj as well (as its code is already included in main.obj).
This is because in main.obj you will ALSO have the sayHello() function due to the include!
sayHello.h
#include <stdio.h>
void sayHello(void);
main.c
#include "sayHello.h"
int main()
{
sayHello();
return 0;
}
You probably defined two times this function
void sayHello()
{
printf("Hello World");
}
one in your current file and one in sayhello.c
You must remove one definition.
The problem seems to be that sayHello.c got compiled into an object file called sayHello.obj, and main.c (also including all the source text from sayHello.c), got compiled into main.obj, and so both .obj files got a copy of all the external symbols (like non-static function definitions) from sayHello.c.
Then all the object files were supposed to get "linked" together to produce the final executable program file, but the linking breaks when any external symbols appear more than once.
If you find yourself in this situation, you need to stop linking sayHello.obj to main.obj (and then you might not want to compile sayHello.c by itself into its own object file at all).
If you manually control every step of the build (like you might when using the CLI of your compiler), this is often just a matter of excluding that object file from the invocation of the linker or compiler.
Since you are using Visual Studio, it's probably making a bunch of assumptions for you, like "every .c file should be compiled into its own object file, and all those object files should be linked together", and you have to find a way to circumvent or disable this assumption for sayHello.c.
One easy and somewhat idiomatic solution might be to rename sayHello.c into sayHello.c.inc.
//THIS IS THE MAIN FILE//
#include "test.c"
int main()
{
multi(10);
}
//THIS IS THE TEST FILE//
#include<stdio.h>
void multi(int a)
{
printf("%d",a*2);
}
POINTS TO BE NOTED:
Here you need to run the program which contains "main()" function.
You can avoid the "stdio.h" header file in main function. Because, you are including the file which already contains the "stdio.h" header file.
You have to call the function from the "main" file.
The including file should be "file_name.c" not "file_name.h". Because usually we use .h extension for the header file. Since we are including another program file and not the header file, we have to use .c. Otherwise it will give you Fatal Error and the Compilation gets terminated.

Resources