C++ Struct prototyping in separate header file

483 views Asked by At

I am having trouble understanding an answer I saw in another post. It said that it is good practice to define a struct in a separate .h file so it can be used in other files. I think that is great and it solves my current dilemma, however I have a question about compilation and makefiles. I am only familiar with having header files that are associated with .cpp files at the moment.

Can someone explain how that implementation would look when I have a .h and no .cpp? Do I need an implementation file as well? Also, how do I link the header in a makefile? Currently I only know how to compile a .cpp & header into a .o file and link them.

Thanks, and sorry for taking us back to c++ kindergarten. This is a new revelation and seems like a good one.

2

There are 2 answers

1
Stefano Sanfilippo On BEST ANSWER

The key concept is that you define the struct/class in a .h header, so that you can use it in multiple .cpp files. Whenever you need struct foo defined in foo.h, you #include "foo.h". You don't need to directly compile the header file, it will be pulled in by whichever source file uses it. Therefore you don't need a make target for .h in normal circumstances.

If the definition in the header is never used, it won't be pulled in and that's it.

1
Mr.C64 On

You don't need a matching source file (.c or .cpp) for every header .h file.

Having header files without corresponding source files is just fine.

When you #include some header file, you can think of it as a kind of "copy and paste" operation: the preprocessor copies the content of the header file, and pastes it in the point of inclusion.
(Well, there are some details to consider here, for example the presence of a #pragma once directive or some #ifdef inclusion guard can prevent multiple inclusions of the same header file in a given project.)

The C and C++ compilers will then process the whole "compilation unit", i.e. the current source file with all the included headers.