Needing some quick tips on how to organize my code

Started by
19 comments, last by dmatter 10 years, 1 month ago

I've been learning C++ from a book lately and I've been making something of a console game/thingy, and a map editor for it... Whatever it is I'm just coding and it's being fun and interesting, but I've coded it all in one file, both because I wasn't expecting to get so far with it, and because I don't know any better. At some point I moved all the declarations into a header file to make it easier to tweak things without as much hassle, but it's still being a huge hassle, it's becoming too much to cope with. I'm well over 2000 lines of code (on the map editor alone, including comments and garbage), and I'm finding it too confusing. An example of a side effect I found was that I was assigning values to the same variable from three different functions during the initialization. But I'm finding it hard to detect and fix stuff like this in all of this mess.

So I need to separate my code into more files, but I haven't learned anything about classes or even header files yet. I "know" what they are and what they're for, but I can't make them on my own yet. So what I need is a quick (and maybe dirty) way to just break up the code and make it bearable, because if I stop working on it I'll eventually lose motivation to keep learning. It doesn't matter if it's a cheap thing to do, the project isn't important, it's just a way to get my hands dirty and learn from mistakes. Like my father said once, analogously, your first car is for you to break.

So if anyone could give me some hints or thoughts on how to go about separating the code into more .cpp or .h files I'd really appreciate it. My biggest problem is with avoiding calling the same header file from several files, I think. But I also feel confused on things like, should I just create header files, should I just create cpp files, should I create both as needed, and how do I determine if they're needed, and how exactly do I make the code from one file interact with the code from the other...

Any help is greatly appreciated. Thanks.

I created a pointer of type Toilet so I don't have to go to the bathroom as often.

Advertisement

I'm sorry, I don't know if this will help, but I found it a while back and thought it was an interesting article about C++ Project Structure. http://hiltmon.com/blog/2013/07/03/a-simple-c-plus-plus-project-structure/

Quite simply the best way (both short and long term) will be to learn the basics of classes and how to use them. They are not very complicated, you can probably learn the basics in a day or two. The key thing about classes is that generally you write them so that they are responsible for doing one single task. I.e. a file parser or graphics controller. You mentioned that you were having trouble keeping track of which variables were being used where and this is another example of what makes classes helpful is that nothing else can touch a classes local variable unless you let them which means that only that instance of the class can read/write it saving lots of confusion later on.

-BiT


So if anyone could give me some hints or thoughts on how to go about separating the code into more .cpp or .h files I'd really appreciate it.

You might start with identifying related bits of functionality (e.g. graphics, ui, file IO, etc) and moving them out to their own files.

My biggest problem is with avoiding calling the same header file from several files, I think.

That's not an issue, there's no reason to avoid calling the same header multiple times. You just have to make sure that it's guarded (either with #pragma once or pre-processor guards).

But I also feel confused on things like, should I just create header files, should I just create cpp files, should I create both as needed, and how do I determine if they're needed

Source (.cpp) files usually contain actual code.

Header (.h or .hpp) files usually contain declarations.

A source file usually has a corresponding header file, to declare all its functions/classes/whatever. You almost never have a source file by itself (A notable exception to this rule is that you might well not create a header that corresponds to the source file containing the main() function).

Occasionally you have a header by itself (without a source file), if you only need some declarations, or are dealing with inline code only, or are dealing with templates.

and how exactly do I make the code from one file interact with the code from the other...

Your header and source files can #include other header files (the declarations of functions, etc). That way they gain access to that functionality. The functionality is implemented in other source files. But you never ever #include a source file. The 'top level' source file would be the one with your main() function it it.

Example:

Graphics.h - Declares functions for doing graphical stuff

Graphics.cpp - Will include Graphics.h and will actually have code to implement those functions/classes.

MapEditor.h - Declares functions for doing map-editory stuff

MapEditor.cpp - Will include MapEditor.h and will implement those functions. May also include Graphics.h to access the graphicsy functions (or it might be that some of these things were also needed in MapEditor.h in which case the header would include Graphics.h and then the source file will gain it just by including MapEditor.h).

Main.cpp - Defines your main() function, includes MapEditor.h to gain access to the map-editory stuff.

My personal experience was similar to yours. I started programming with really basic C, that could all fit in one implementation file or, at most, the implementation and a header. To step forward, I had a tough time, since I didn't really know what the problem was (what exactly I wasn't grasping).

I started to study C++ and Object Orientation, and that gave me an overview of modeling and architecture. I was then able to separate my code better, so I did with the files.

But the only time I really learned to structure my files was when I started to use an IDE. I had been using notepad++ and a command line compiler. I started to use the IDE templated file creation features to create files with some pre-defined code (such as the basic class structure and this kind of stuff); it forced me into a good style, somehow.

So, study more, it will suddenly become clearer. It is kind of like learning a new spoken language; one day you can't understand anything you're hearing, but the next one you can't believe you understand almost everything.

A class is just a group of functions and variables tie together to acheive a specific goal if you think about it. Nothing complicated about that. For example, i often create an OpenGL class to handle the graphic side of an application or game, this class is responsible for everything opengl related and nothing more. It usually have functions like InitOpenGL(), ShutdownOpenGL(), LoadTexture() and FreeTexture(), Render() and Update() ect. For small project you usually don't need more than a few, or even none, but as the project grow larger it's usually best to start splitting things up into classes.

Take a look at this, that's my main code library i've built over the years, don't look at the code but focus on the files names, every one does a specific tasks. The code in .h files are a little weird since they was initially used in multiples languages as a dll, hence the weird bits, but you get the idea. Also a lot of them aren't used frequently (or at all) but some of them are really usefull (especially FileIO and RawBuffer).

Thanks everyone for the responses. It's being quite insightful. I'm going to try some stuff tomorrow.

I've also just found an article that may also be helpful, though not today. smile.png

@Vortez, about the classes, I have... some degree of awareness on how to make them and how to use them, since I was starting to use them in actionscript 2 a few years ago before I stopped coding then. But there's two problems: 1- I always just create a bunch of files and end up staring at them indecisively, due to not quite having an idea where to put what, and 2- I'm not yet familiar with c++'s syntax for classes and their baggage. I skipped a bit in the book I'm reading to quickly get to pointers, but I'm intending to get back to what I skipped (structs, enums, and more on strings). I don't want to rush it.

@dejaime, well... I'm extremely (really) picky when it comes to colors. I can't stand writing code in a white background, and I like to just get my hands dirty when I'm learning something. All the IDEs I tried (well, CB, VC and DC, don't know any others), kind of got in the way of it. There's always something that needs to be set or some intricacy that needs to be understood (i.e., project templates, MS's main() arguments), or otherwise something that doesn't work for very specific reasons. I've been away from C++ for years because of this. Also, they clutter my hard drive with project folders (VS is particularly unorganized, it mixes projects from all apps in one folder by default) when all I want at this point is a source file to experiment with. When learning the basics, I need a basic setup to get right down to it and keep me focused and without obstacles.

To that end I'm using Sublime Text for now, which seems to work well so far, though I see times where an IDE would be beneficial. But I find that those apps aren't much good at replicating the level of customization from ST, sadly. ST is great in it's keyword highlighting and dark background, it makes me feel extremely comfortable. So, at least for now I'm stuck with it. That said, I'm still using CB to, for example, compile tutorials I'm following on SDL. I code them in ST and compile them in CB. I still think it's too early for me to be delving into their distractions. I rather be reading the book instead of losing time with the IDEs.

EDIT: By the way, should, or could, variable declarations go on (non-class) header files too?

I created a pointer of type Toilet so I don't have to go to the bathroom as often.


I'm extremely (really) picky when it comes to colors. I can't stand writing code in a white background

We're two then! I am lightly photophobic, and I use a modified version of the C::B theme called Son of Oblivion (a Son of Obsidian port to C::B). I also program with only around 15% brightness on my LED monitor (40% during the day, but I do the huge majority of my coding at night)...

I also search the web with blackle.com, feels better (I don't know if it really saves any energy in LED monitors)

(GD.net is too white, but we can't have everything, can we? biggrin.png )

I assure you, the thing that helped me the most was actually studying Object Orientation. It helped clear where one part of the code ends and the other starts, so it helps define/choose the files I needed/wanted.

But It is a fact that using IDEs helped me further in learning some more. Still, I know some guys to what it did the opposite and made them go on brainless file creation rampages on every project they started!

I also use IDEs for their color schemes, even though Sublime Text is said to be the best here. But as IDEs have a world of more features for C++ development, I can't go with a fancy Text Editor over an Integrated Environment; or else, I'd need to write loads of build scripts that wouldn't be necessary with a full fledged IDE).

I like how C::B handles its highlighting color schemes, maybe I am just used to it...

It also has some neat features for C++, such as active/inactive code highlighting (to name one):

C_B.png

Comment the #define

C_B.png

About variable declarations, they surely can go on header files. If the variables are global, declaring them on the header will be enough, but if they are "class globals" (static class variables) you need to put them in the class definition and then declare them in the .cpp file.

@dejaime, well... I'm extremely (really) picky when it comes to colors. I can't stand writing code in a white background, and I like to just get my hands dirty when I'm learning something. All the IDEs I tried (well, CB, VC and DC, don't know any others), kind of got in the way of it. There's always something that needs to be set or some intricacy that needs to be understood (i.e., project templates, MS's main() arguments), or otherwise something that doesn't work for very specific reasons. I've been away from C++ for years because of this. Also, they clutter my hard drive with project folders (VS is particularly unorganized, it mixes projects from all apps in one folder by default) when all I want at this point is a source file to experiment with. When learning the basics, I need a basic setup to get right down to it and keep me focused and without obstacles.

I would recommend you to reconsider - a proper ide (which Sublime Text at least does not seem to be from my cursory examination) is an invaluable assistance, especially if you are relatively new. And even more so when you are not new and your projects grow to anything above trivial.

I would recommend Visual Studio 2013 (for desktops, express edition - ie. free). Its coloring scheme is highly customizable - comes even with a "dark" theme as a preset option (or a starting point for your own customizations).

Syntax coloring options include separation of: global/local/member/static-member variables, namespaces/classes/enums/types, static/non-static member functions, macros etc...

Intellisense can also automatically pick up and mark with red-wiggles most errors without the need to compile and its hover-tooltips, as you will see below, are quite informative.

An example of my, slightly altered from default, coloring (i prefer white - used to prefer dark when i first started out ~20y ago):

http://postimg.org/image/r0ckj03i7/

edit: Uh, what, why the downvote? That makes no sense.

I like how C::B handles its highlighting color schemes, maybe I am just used to it...
It also has some neat features for C++, such as active/inactive code highlighting (to name one):

Just used to it tongue.png.

I have never used Code::Blocks myself - does it have comparable highlighting options to VS (look my pic in previous post [VS has quite a lot of type separation too - but i have colored almost all of them with the same color])?

The active/inactive code highlighting is obviously present in VS too - and its presence in CB hints that it too might have some Intellisense-esque capabilities, hence the Question.

This topic is closed to new replies.

Advertisement