C++ - need advice on how to properly design a multi-file program -


ok, need create simple game using allegro 5 , c++. want split separate modules it's easier manage. question is: proper way manage "moving" between different files? specifically, i'd have file called menu.cpp, main file , depending on user selects, things specified in other files, singleplayer.cpp or options.cpp (is approach?). idea this:

//menu.cpp #include "singleplayer.h"  int main() { int parameter; if(user_selects_singleplayer) singleplayer(parameter); return 0; }   //singleplayer.cpp void singleplayer(int parameter) { ... handle_singleplayer ... }  //singleplayer.h #ifndef singleplayer_h #define singleplayer_h //or maybe #pragma once  ?  void singleplayer(int parameter);  #endif 

i'd know if it's proper way that, , if so, if should have main() function in singleplayer.cpp (and how change file make work) , if need include singleplayer.h in singleplayer.cpp .

in example omitted stuff including allegro libraries, initializing more variables etc. make general idea clearer. i'd note can't use classes , streams (i know it's stupid, it's requirement project homework assignment programming class).

edit: question linked @leiaz relevant , answers helpful understand how headers work, question more correct design approaches. anyways, answers, read on subject.

here rules should work in situations:

  • every cpp file has h-file included within cpp

    main.cpp includes main.h , singleplayer.cpp includes singleplayer.h

  • class definitions , function prototypes in header file, implementation in cpp file

    h: int add(int x, int y); cpp: int add(int x, int y){ return x+y; }

  • only include header files, never include cpp files

    avoids multiple definition problems, since headers have code guards (your defines) , cpp have not

  • only include files need reduce compile time

    dont make all.h includes each header have.

  • if possible, include h files within cpp files. include in header, if needed there.

    reduces compile time , avoids circular references

you should research on how proper design c++ project understand principles behind it.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -