Search code examples
c++launch

Giving the application some data on launch


I'm trying to create an application that can receive some data on launch from another program. For example:

Start_App.exe calls Main_App.exe and gives it the current date, all at the same time
(while launching it)

Main_App.exe outputs the date on its console

Without the data passed by Start_App the other program can't work correctly or will do something else. I've been searching for a while but it seems like I'm missing the technical names...


Solution

  • You'll probably want to use command-line arguments.
    They are passed by writing them out, separated by spaces, directly after the program name.

    Like so:

    #include <iostream>
    
    int main(int argc, char *argv[])
    {
        using namespace std;
    
        cout << "There are " << argc << " arguments:" << endl;
    
        // Loop through each argument and print its number and value
        for (int nArg=0; nArg < argc; nArg++)
            cout << nArg << " " << argv[nArg] << endl;
    
        return 0;
    }
    

    argc is the number of arguments the program received.
    *argv[] is an array of strings, one for each argument.

    If you call the program like this:

    Program.exe arg1 arg2 arg3
    

    It gives you:

    There are 3 arguments:
    0 arg1
    1 arg2
    2 arg3