2

I would be really grateful if you could help me!

Some time ago, I created with some friends a tiny web-browser game using JavaScript. One of the main problems that we encountered was the big dimension of the "main" file. So we decided to split the "main" file in multiple code files, for example: Globals.js, where we stored all our global variables, Path.js, where we made different algorithms. And so on.

It was extremely simple to work this way - it gave a feeling of structure. Main.js would freely take every function declared in the other code files. We just had to put the JavaScript files in the same folder with the main.js file, and have a nice looking main() function, nothing else.

Now, I'm using Qt Creator, and I'm working in C++. Of course, there is the main.cpp file, the nucleus to say so. How can I declare functions outside the main.cpp file, so that my main.cpp file looks nice, without clutter, and still be able to access the functions?

zmx
  • 1,051
  • 1
  • 10
  • 12
  • 1
    You should consider using C++ classes. However, if you don't want to do that, you can define your global function in a header file, like foo.h and than include it in your main.cpp as `#include "foo.h"`. This is the rough solution, though. – vahancho Apr 30 '14 at 13:12
  • Ok, thank you! I searched a little more and found details of what you have said. I'm going to try with it. http://stackoverflow.com/questions/6995572/using-multiple-cpp-files-in-c-program – zmx Apr 30 '14 at 13:17

1 Answers1

1

Well, you have two options, basically:

1) Declare them in the main.cpp where your main function resides.

2) Declare them in separate files, but include their headers, or use extern for introducing them in your skype.

In general however, Qt is an Object Oriented C++ framework, so you would be dealing with classes unless you use free standing functions for global operators, etc.

I will try to represent the idea here with simple snippets:

foo.h

void foo() {}

main.cpp

#include "foo.h"

int main() { return 0; }

Defining them all in the main.cpp is also possible as follows:

main.cpp

void foo() {}
int main() { return 0; }

That is pretty much to it. You will links where they put the definition of "foo" after the "main" function, and they only declare it before, but in general, it is better to avoid that. It does not only add extra code, but it does not make the dependencies clear between functions either as opposed to ordering the definitions in roughly dependency order.

That being said, one of the most common main functions in the Qt world would look something like this though using classes:

main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char** argv)
{
    QApplication application(argc, argv);
    MainWindow w;
    w.show();
    return application.exec();
}
László Papp
  • 51,870
  • 39
  • 111
  • 135