Making header files

This is a discussion on Making header files within the C++ Programming forums, part of the General Programming Boards category; Hello!!!!! I was reading about header files, and wanted to learn how to make them, because it seems like it's ...

Making header files

Hello!!!!! I was reading about header files, and wanted to learn how to make them, because it seems like it's a lot more organized, and helps compile long projects faster. But I don't know the exact name of what I should be searching for. Should i search for preprocessor, inline, or is headerfiles the correct name? A tutorial would be nice.......but just a better understanding of what a header file does would be cool too.

But, you also have another option for organizing your files. You can remove the function definitions from the main() file and organize them in separate files. For instance, you might want to organize your functions into files called:

my_functions.cpp

functions_I_got_from_my_friends.cpp

functions_I_got_from_my_teacher.cpp

You can imagine how hard it might be to navigate around a main() file that contained 200 function definitions. You would have to scroll up and down the file hunting for the code you were trying to find.

Now, suppose your function my_func() is defined in a separate file named my_functions.cpp. If you do this:

Code:

int main()
{
my_func();
return 0;
}

you'll get an error just like before because the compiler doesn't know what my_func() is. So, you need a way to put the function declarations above main() somehow--just like in this example:

after the compiler gets done compiling my_program.cpp, the file will look like this:

Code:

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

The compiler won't complain since it sees the function declaration somewhere before the line where the function is called. However, if you notice, there isn't a function definition after main() like in one of the earlier examples. That's ok, though, because when the definition of my_func() isn't found after main(), something called the linker will examine all the other .cpp files in your project until it finds the definition for my_func().

To summarize: if you want to organize your function definitions in separate files from main(), create a header file for each .cpp file that contains your function definitions. In the header file, type out the function declarations for each function definition in the corresponding .cpp file. If you have two .cpp files with function definitions, then create two header files with each header file containing the declarations of the functions in the corresponding .cpp file. Then, include each header file at the top of your main() file.