Question about header files and adding additional cpp source files.

Pages: 12
So im writing a program and it's getting annoyingly large in size where im having to scroll through lines and lines of code to get anywhere. Its time for me to learn how to use header files and additional cpp source files.

I read up on it a little and tried it with my program and noticed a few things. I dont have any code snippets yet. Just general questions for now and im asking in terms of whats good practice or proper.

What are header files generally used for? Shared code? What usually goes inside of the header files? I read function prototypes and classes, but im assuming anything o want to easily share among source files.

When i began splitting up my pne big program into separate source files, i noticed that i need to include everything thats in the main source file, such as all the #includes etc because i was getting crazy errors. It makes sense but initially i didnt think id have too. I tried to put all the includes or shared stuff in the header file and just include that header fioe with all the separate source files but onwas still getting errors. Just seems redundant having to add all that stuff for each source file.

Now... I learned real quick that im going to need to create more global variables and start passing more arguments because a lot of my variables were unrecognized. My old C++ teacher saod to limit the number of global variables becuase they are vunerable. Whats better practice?

I have a whole bunch of subroutines or functions i made for this program. I want to put them all in a separate file of their own. Shouod i place them in a header file or a separate source file?

Thanks for all of your help.





Last edited on
Hi

Put the class definitions and function declarations into header files, a common naming convention is *.hpp for cpp header files.

Put the implementation code for the class functions and ordinary functions into *.cpp files.

one can read about here: https://cplusplus.com/doc/tutorial/classes/

Now... I learned real quick that im going to need to create more global variables and start passing more arguments because a lot of my variables were unrecognized. My old C++ teacher saod to limit the number of global variables becuase they are vunerable. Whats better practice?


Having lots of global variables is definitely a bad idea, your teacher is right. Structure your program so that you pass arguments to the functions that need them. Also try to limit the scope of the variables to only where there are needed.

I have a whole bunch of subroutines or functions i made for this program. I want to put them all in a separate file of their own. Shouod i place them in a header file or a separate source file?


To start with, if you have classes, ask yourself if any of your functions belong to a class? A beginning and basic concept is that a class comprises of some data variables, and functions that operate on those variables*, but that is not the whole story - not all functions need to be part of a class. One example is if a function can use a classes interface functions, then it doesn't need to be part of the class.

My advice is to start out small: Have one class that does the simplest thing, get that right, then move on to create other functionality.

* Beginners often think that classes are a simple idea, like above, but actually things can get complex. Here are some things to research:

Does everything have to go into a class? No. How much inheritance to have? Too much is bad. How to structure the inheritance? Can one factor things out of classes to improve the extensibility and scalability, and to reduce coupling? Yes, there are things called design patterns, and design principles. When and how should one make use of polymorphism? What is an interface? Should I put my interface functions in their own class? Probably, yes. What are class invariants? What is a Validation class , should I have one? Probably, yes. Can I use a Validation class to enforce contract programming? Yes.

https://en.wikipedia.org/wiki/SOLID
https://en.wikipedia.org/wiki/Software_design_pattern

Consider buying a good text book:

https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list


https://en.cppreference.com/w/cpp/links

If the functions/classes are templated, the implementation/body goes with the header. You don't split templated code into declarations/implementation files.

Design first - code last. Code in small chunks. Compile and test frequently.
Last edited on
> What are header files generally used for? Shared code? What usually goes inside of the header files?

Get a copy of (and peruse) 'Large-Scale C++ Software Design' by John Lakos.
https://www.amazon.com/Large-Scale-Software-Design-John-Lakos/dp/0201633620
Published in 1996, but it deals with issues that are still very relevant.

Google styleguide on headers: https://google.github.io/styleguide/cppguide.html#Header_Files
I don't agree with all of it; for instance with, 'Avoid using forward declarations where possible.'

Coreguidelines on source files: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#S-source
John Lakos also gave a talk about Large-Scale C++ Software Design
https://www.youtube.com/watch?v=K_fTl_hIEGY
Last edited on
When i began splitting up my pne big program into separate source files, i noticed that i need to include everything thats in the main source file, such as all the #includes etc because i was getting crazy errors. It makes sense but initially i didnt think id have too. I tried to put all the includes or shared stuff in the header file and just include that header fioe with all the separate source files but onwas still getting errors. Just seems redundant having to add all that stuff for each source file.


Only include the header files you need for that file. Never include cpp files. Make sure you have header guards, and / or #pragma once

Putting all the includes into one file sounds like a bad idea to me because it looks like it's going back to having one "God File", which is what you should be avoiding.

Also, consider putting your code into one or more namespaces. They are for helping to separate code to avoid name clashes for variables and functions.

Try to avoid using namespace std; especially in header files. Just put std:: before every std thing. It is not the only way of doing it, and it sounds harder, but it is better in the end, and it is what most experienced c++ coders do. There is lots written about this ad nauseam on the web.

Investigate using code snippets, it makes typing so much easier.
Last edited on
I have a whole bunch of subroutines or functions i made for this program. I want to put them all in a separate file of their own. Should i place them in a header file or a separate source file?


Well we moved away from split .h/.cpp files to .hpp files. In the .hpp files we put the whole function/class definition (and their bodies) and mark stand-alone functions as inline - with #pragma once at the top. Any code that uses them just then needs to have the appropriate #include statement. With modern C++ compilers, this doesn't impact compile times and there no issues re linker duplicate/template errors etc. Each .hpp file has the required #include for that .hpp to compiler. Works well for us. Easy Peasy.......
Well we moved away from split .h/.cpp files to .hpp files.

Works well for me. There is no need to jump around to keep files in sync, reducing future maintenance work. Having fewer cpp files in a project makes it easier to focus on application logic.

The hpp approach works the best if precompiled header is used. A vast majority of code in hpp files is compiled in an instant so a compiler simply focuses on compiling some code in cpp files.

Save a lot of time, faster development.
Last edited on
For the latest VS IDE, you don't need to set Use pre-compiled. The compiler knows which functions etc in the whole compilation unit need recompiling. We've turned off pre-compiled. Using this can also cause issues...


eg from a VS compile:


3 of 260 functions ( 1.2%) were compiled, the rest were copied from previous compilation.

Last edited on
seeplus wrote:
Well we moved away from split .h/.cpp files to .hpp files.


I guess the OP, as a beginner, should learn both :+D
Agree, learn both. There are times when you can't just inline everything in the hpp.
All that said, "pre-compiled" will not benefit any small projects since VS IDE compiles them very fast (it does not necessarily have to be latest VS IDE).

It is when a project uses a large header-only library (hundreds of hpp files), even if a compiler is very smart to reduce compile time is various ways, the result wait time is still significant. Using "pre-compiled" helps a lot in this case.

Since it takes me like 10 seconds to see "the rest were copied from previous compilation", presumably the VS IDE still has to visit all header files then do some light checks to either fully compile or skip compiling functions.

Since I look forward to saving my time for my own good, I leave pre-compiled on.
> There's an updated version by John Lakos (Jan 2020).

The 1996 classic is way better.

This new book is a lot more about 'this is how we do things (name files, structure directory trees etc.) at Bloomberg'. Has a lot more verbiage, and less clarity. There are a few updates to the language; but even in the 2020 book, the overall treatment of C++ is still dated.
What are header files generally used for? Shared code? What usually goes inside of the header files?

You put forward declarations in header files then have several cpp files split one big giant cpp file and you will have smaller, more manageable cpp files to work with.

If you make fully reusable functions on which multiple projects can rely, make them inline functions in header files and do not use forward declarations.

Header files are created and used to make shared code easily accessible, thus one can avoid reinventing the wheel many times in order to focus on more important things.
I guess the OP, as a beginner, should learn both


Yes. The issue I have though, with C++ teaching in general, is the order in which things are taught. C++ isn't 'C with bits added on' as many teachers/professors seem to see it and teach. C++ is it's own language and IMO should be taught as such. vector before c- arrays, string before c-style strings, managed pointers before raw pointers, algorithms etc etc etc.


@seeplus, you highlighted one of the biggest "gripes" I've got with about what passing for C++ instruction. Too many people who come here looking for help, wanting "Old School C++ As C" help.

Not that it is THEIR problem, they haven't been taught better, and it shows.

That includes using namespace std; or the C library random routines. *SPIT*

@CVRIV, if you haven't already poked around the online tutorials here at CPlusPlus and Learn C++ I seriously suggest you make some time.

http://www.cplusplus.com/doc/tutorial/ (Dated, little C++14 with nothing on C++17/20/later, and not likely to be updated any time soon)

https://www.learncpp.com/ (Is frequently updated, and is a better C++ tutorial IMO)
I bought the 1996 book mentioned here. Ya'll really confused me. I'm picking though all this info trying to gather what I can in understanding.
I think TheIdeasMan's first post is the most important takeaway.

Asking questions that are as focused as possible will get you answers that are as focused as possible. If you ask too many questions in one post, it's hard for people to answer them without going into tangents (and for the questioner themselves to not go into tangents). Try to make your questions concise and without typos.

Here's my try, which I make no claim will be better than others:
What are header files generally used for? Shared code? What usually goes inside of the header files? I read function prototypes and classes, but im assuming anything o want to easily share among source files.
Yes, generally you'd expect a header to be #included in more than one place. I think a better word than "shared" code would be "reused" code. Functions and classes are really all you need to focus on at this point (and the occasional enums and global constants).

The purpose is code organization. You could have everything in one huge file, but this is hard to scroll through and really just overwhelming. When your codebase grows, you'll have entire sections of the codebase that are dedicated to, say, the user interface, and another section dedicated to some SQL database, and another section dedicated to maybe networking. And each "section" of code may span multiple files. Having all of these different areas of the code all in one file would be very hard to reason about and organize.

i noticed that i need to include everything thats in the main source file, such as all the #includes etc because i was getting crazy errors
This applies to many other areas of programming: Start small. Don't try to refactor all your code at once to use multiple files. Focus on just one class or function at the start. Start with a small program just to test out the idea of working with multiple files, following tutorials.

If you start out with a small program and experiment with it, others will be able to help you much easier when you have trouble.

Whats better practice [than global variables]?
Pass variables by arguments. Encapsulate groups of variables that belong together in structs/classes, and then pass the single struct/class as an argument. Slowly build up from there.

Shouod i place them in a header file or a separate source file?
The important thing is separating them out into different files. Whether you choose to have them all be inline in the header vs. separated into separate .cpp files is less important. There will be times when you'd be forced to separate out things into implementation files, so it's good to be familiar with it (such as two-way referencing, e.g. a Person needs to know what a Dog is, and a Dog needs to know what a Person is).
Last edited on
Furry Guy wrote:
@seeplus, you highlighted one of the biggest "gripes" I've got with about what passing for C++ instruction. Too many people who come here looking for help, wanting "Old School C++ As C" help.


I agree. We have a lot of traffic generators on this site, probably a lot of them are spambots. They post shitty code because they know it will create the most reaction. Fortunately we have some expert members who post really good code and awesome advice, so others can learn.

CVRIV wrote:
Ya'll really confused me. I'm picking though all this info trying to gather what I can in understanding.


There is a life time of learning with C++, partially due to there being a new standard coming out every 3 years; but also because it's not just the syntax, there is so much to learn about design, idioms, principles, practices and patterns.

As mentioned earlier, start simple, design first, write pseudo code if it helps, code small amounts, compile frequently, test often. So that all means 1 function at a time.

Try concentrating on just using the STL - there is a tremendous amount one can achieve by doing this. Prefer to use STL containers like std::vector, classes like std::string, and any of the std algorithms.

Also investigate version control systems, like git, hopefully there is integration with your IDE, so it is easy to use.

Finally, try things out - if you have any questions, then ask them here - plenty of people to help out. So that includes questions about your design, get that right first.

Good Luck !!
Pages: 12