Whats the best way to organize MANY functions?

Im working on a personal project with at least 20 (probably more) user-made functions. What's the best way for me to go about organizing them? Should I create a .h and try writing them out in header? Or try a separate .cpp?

So you know, I haven't worked much with header files, and I've never tried using a reference .cpp. I've always looked at using a .cpp to be exploitative when it comes to taking the place of a header. If I'm wrong, show me otherwise! (if you can)

Thanks.
closed account (3hM2Nwbp)
I use this answer way too much, but I would have to say that the best way is: it depends! We'll need to know a bit more about your specific situation to give a clear-cut answer, but generally the interface (*.h) is separate from the implementation (*.cpp), as seen below.

1
2
3
4
5
6
7
// ExampleHeader.hpp
#ifndef EXAMPLE_HEADER_HPP_INCLUDED
#define EXAMPLE_HEADER_HPP_INCLUDED

int exampleFunction(int, int);

#endif 


1
2
3
4
5
6
7

// ExampleHeader.cpp
#include "ExampleHeader.hpp"
int exampleFunction(int a, int b)
{
  return (a % (b + b * a) / (a * b + 1)) * 0xBADC0DE;
}


If however, you're using templates, it's a bit different. If that's the case let me know and I'll throw an example out. One other possibility is using a function mapping solution (if your public API would be best suited with it).
Hmm. Let's just say... I have written out a lot of my functions in a Word document. Most of them contain rand() functions, such as srand(time(0)) for example, which taps into the time.h header, and possibly (eventually) a few others. Im not too fond of including that into a new header for my code.

Aside from there being a number of declared variables, there isn't much thought needed to understand my functions. It's mostly childs play.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void buildhp(int& hp)
{
  srand(time(0));
  hpPercent = rand() % 6 + 1;

  if(hpPercent == 1)
  {
	hp += 2;
  }
  else if((hpPercent >= 2)&&(hpPercent <= 4))
  {
	hp += 3;
  }
  else
  {
	hp += 4;
  }
}


Here's maybe a better way for me to spell things out... I don't want to have to declare all 20+ of my functions in one single .cpp WITH the rest of my source code in the main(). So, how can I go about organizing all of my functions, variables, ect. so that I don't end up getting confused and lost in my own code due to the endless void and integer returning functions that I may have.
Last edited on
closed account (3hM2Nwbp)
Im not too fond of including that into a new header for my code.


Do you mean that you are wary of including <ctime> in multiple header files? If that's the case, then don't worry about it. Include where you need to and let the compiler sort out the rest.

When it comes to how to organize your functions (API) over multiple files, just do what you feels makes sense. Say you have a group of functions that deal with running different calculation formulas for your program, you could put them into a header/implementation pair named "Formula.hpp" and "Formula.cpp", respectively. Then, in your main source file.

1
2
3
4
5
6
7
#include "Formula.hpp"

int main()
{
    srand(time(0));
    // use methods in "Formula.hpp"
}


PS. You should only call srand once in your program, possibly as the first line in your main method. This method seeds the random generator and only needs to happen once.
Last edited on
Nice note on the srand I never knew about it. And yes, I'm more concerned about organizing them all into the same file. I would like to somehow be able to call the complete functions into my primary file from another. And by complete, I mean the function as a whole all in the same file, which would be a header or separate cpp. I know that sometimes they can be written between different files, which is what I am trying to avoid. So I guess that would be what you demonstrated with the Formula.hpp
closed account (3hM2Nwbp)
If you really want to keep the interface / implementation in the same file, then you could use a header-only approach. Keep in mind, however, that as your projects grow larger, compilation times may skyrocket with a header-only design because a seemingly simple code change would require more translation units to be recompiled.
Just to confirm, you're saying that if I choose to take the header approach that I should be cautious of the amount of variables and units I declare, because it may create slower loading times and/or confusion within my code or between files?

Thanks.
closed account (3hM2Nwbp)
Oh, not at all. Here's a scenario where the compilation times would increase.

Say you have a header "Point.hpp" - which holds a class of a 2 dimensional point. Now say that you've included "Point.hpp" in 1000 other files and you change (even a little bit) "Point.hpp". Now all 1000 of those other files have to be recompiled just because of the one header that was modified. Separating the Point example into headers and implementation files would allow you to modify "Point.cpp" without having to recompile every file that includes the Point header. I used the term "translation unit", which you might not have heard before. A translation unit is basically a source (*.cpp) file after the preprocessor gets done with it. Try not to be too overly concerned with declaring variables and such. Write your program in a way that's easy to understand and maintain - leave the optimizations to the compiler.
Last edited on
OOP
So for example, if I were to organize all of my functions into one header I could write them out like this?:

1
2
3
4
5
6
7
8
9
10
void hpadder(int& hp)
{
hpPercent = rand() % 6 + 1;
if(hpPercent == 1)
{hp += 2;}
else if((hpPercent >= 2)&&(hpPercent <= 4))
{hp += 3;}
else
{hp += 4;}
};


If that's correct, can't I just call it from to header to my .cpps? ...Im so lost with what to do with these functions in a header!! *massages forehead*
Now that I've looked it over... I'm doubtful that that's correct -_-

I'm confused with where AND how to define my functions and write out their contents. I want to be able to just include the file which contains the function's code, similar to that of a script repository, and then call the function into my primary program of use. For example: hpadder(blah blah blah);

I feel like that method may be the best way for going about my issue.
Last edited on
For example, for that hpadder function, you could do something like this:

1
2
//the h file
void hpadder(int& hp);


1
2
3
4
5
6
7
8
9
10
11
12
#include "what_h_file_is_called.hpp"
//the cpp
void hpadder(int& hp)
{
hpPercent = rand() % 6 + 1;
if(hpPercent == 1)
{hp += 2;}
else if((hpPercent >= 2)&&(hpPercent <= 4))
{hp += 3;}
else
{hp += 4;}
};


Now you can just include what_h_file_is_called.hpp wherever you need to use the function.
I don't want to have to deal with a lengthy cpp. I want the h file, or SOME other file to be responsible for carrying out the function's directions, while my MAIN program, the one that pieces everything together, only relies on me calling them instead of sorting through 20+ written out functions in itself. That's like 300+ lines of unnecessary code that I would have to write in a cpp file, which I may eventually use again, giving me another reason why it would be nice to have it in a separate file.

Basically what I've been trying to say in detail is that I would like to not have everything be one huge confusing mess within my "more important" program which would be my primary executable.
Last edited on
Generally .h files don't perform functionality. They are header files with the purpose of publishing to users what types and functionality are available. Accompanying .cpp files provide the functionality. Using these files appropriately help reduce code and reduce complexity. That seems to be what you're looking for.

Take the large ugly mess of functions, and put them in individual .cpp files. You can also put more than one function into a .cpp file, particularly if you see strong similarity of functions.

Then, copy all of the function declarations and put them into a single header file, like "functions.h". Each of the .cpp files (including main.cpp) will include this header file.

When you are done, compile each of the .cpp file down to an object file, and then link all of the objects together to create an executable. There are more steps in compiling this way, but an IDE will take care of this for you automatically, and you will have smaller, less complex, more maintainable code to work with.

As you work with your code, you will see which functions go together. You should group those functions together into their own header files, and include that header file wherever those functions are needed or defined. So if I had the functions:

getUserInput()
drawSquare()
getUserName()
calcSpeed()
getUserPassword()
drawCircle()
drawPoint()
waitForSignal()
saveFile()

I would have at least 3 header files, 1 for user interactions, 1 for drawing, and 1 for general functions. The .cpp files that need to get info from the user and the files that define the getUser...() functions would include getUserInput, etc. (This example is a bit contrived and I probably wouldn't do it exactly this way, but hopefully you get the point.)

A benefit of this is that if you change the implementation of a function (fix a bug, perhaps), but don't change its interface, you only need to recompile the .cpp file containing the implementation and then re-link everything. The .cpp files that merely include the header file don't need to be recompiled. Using an IDE usually takes care of this automatically, but if you are compiling by hand, Makefiles can be set up to take care of managing the dependencies for you.

But, this is C++, and as therockon7throwm said above, you should probably learn about object oriented programming. If you gave us some details of what you are working on, we could help you figure out how to put it into the OO framework, and how that would further help to declutter your code.
Im trying to create a small game, similar to a RPG game where the player levels up and increases in stat points. That alone says that there are going to be A LOT of variables involved and many needed functions. I want to use this game as a learning experience for connecting multiple C++ files, and testing my overall gained knowledge while learning more along the way.

And for curiosity... that's just how I do things. I set up challenges for myself that are a couple steps above my skill level. That way I'm constantly learning, while applying bits and pieces of what I already know as practice. It takes some time, but it ensures that I learn it and understand it. So thanks for the help so far; however, I could use a little more.
Are you familiar with classes? The tutorial on this site has a good chapter on them:

http://cplusplus.com/doc/tutorial/classes/

That chapter covers the basics. When you understand them, you can move on to the more detailed topics in the tutorial under the "Object Oriented Programming" heading:

http://cplusplus.com/doc/tutorial/

Classes are the basis of object oriented programming. They encapsulate groups of data and the functions that operate on that data. In your RPG, for instance, there might be a class called Player that contains data such as health, level, weapon, stat points, etc. All of the functionality associated with the Player would be contained within the class. For instance, there might be a battle() function that looks at the Player's weapon for input, and based on results could modify the Player's health and stat points. Or something like that.

(Note: This is just an example. I don't write RPGs, so I really haven't thought through whether this would be a good design approach. Others on this site do and would be better help with design questions.)

Potential classes in your design could be:
Room (different locations in your game)
Map (A graph of Rooms and how to get from one to another)
Weapon
Enemy
Treasure
Knapsack (knows how much treasure or other items can be carried)
etc.

You can write and test each class in isolation before integrating all of them into your final project.

And when you write a class, generally you put your class definition into a .h header file, and all of the member functions into a .cpp source file.

MyClass.h:
1
2
3
4
5
6
7
8
class MyClass
{
public:
    MyClass(int value);
    void increment();
private:
    int a;
};


MyClass.cpp
1
2
3
4
5
6
7
8
9
#include "MyClass.h"

MyClass::MyClass(int value) : a(value)
{ }

void MyClass::increment()
{
    a++;
}
Cool. That sounds like a great approach for me to experiment with. Other than that, how would one go about connecting all of the "class.h" and "class.cpp" files into one big interconnecting mothership file/program to produce an executable to run?
Last edited on
Topic archived. No new replies allowed.