[Solved] Specify a ‘Main’ class as the first to load [closed]


“When I create the first class what do I put into it so that, when the program is run, that this class loads first?”

C++ uses the same concept as C does for the entry point of an executable program (int main()):

class MyMainClass {
public:
    void run() {
         std::cout << "MyMainClass running ..." << std::endl;
    }
};

int main(int argc, char* argv[]) { // This is the main entry point of a program.

    std::cout << "In main() ..." << std::endl;

    MyMainClass x;
    x.run(); 
}

Output

In main() ...
MyMainClass running ...

Here’s the live sample.

So there is no class that loads first automatically. You have to create an instance and call a member function of that class

If you build a program as an executable, it’s linked with the program startup code (usually crt0.o), that contains some routines to initialize your program’s memory context, and binds to parameters passed in by the diverse exec() OS calls.
This startup code will at last call the main() function, that is marked for external linkage there.

Thus you’ll need to provide a definition for the main() function when linking the executable (no matter, where this comes from, your main.cpp or another library linked in).


“so when the program is ran it will run that before anything else?”

To detail on that question you asked in your comment:

The mentioned startup code for C++, includes that constructors of statically instantiated class/struct objects are called even before main() is executed, thus NO. If you have the following code MyStruct‘s constructor will be called before main():

struct MyStruct {
     MyStruct() {
         std::cout << "Construct MyStruct ..." << std::endl;
     }
};

static MyStruct s;

int main() {
    std::cout << "In main() ..." << std::endl;
}

Output:

Construct MyStruct ...
In main() ...

Here’s a live sample.


“Then how to I set a main .cpp file to initialize first?”

As you’re asking how this is organised in eclipse (eclipse-cdt I assume):

Eclipse CDT lets you have several projects within a workspace. The usual way to go is

  1. Have one or more C++ library projects (shared or static) containing all of the classes definition code.
  2. Have at least one C++ executable project that links in the library (stubs) created with the other projects in that workspace, and provides a definition for main().
  3. It’s a very common technique to have a separate executable C++ project, that acts as a unit test runner for the classes declared and defined in the C++ library projects.
    It’s possible, that the unit test framework library already provides a suitable definition for main() (e.g. googletest provides this option).

1

solved Specify a ‘Main’ class as the first to load [closed]