简体   繁体   中英

How to declare functions outside main.cpp file in Qt Creator

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM