C++ – How to accept arguments in the main.cpp file and reference another file

clinuxprogramming practicesUbuntu

I have a basic understanding of programming and I currently learning C++. I'm in the beginning phases of building my own CLI program for ubuntu. However, I have hit a few snags and I was wondering if I could get some clarification. The program I am working on is called "sat" and will be available via command line only. I have the main.cpp.

However, my real question is more of a "best practices" for programming/organization. When my program "sat" is invoked I want it to take additional arguments.

Here is an example:

> sat task subtask

I'm not sure if the task should be in its own task.cpp file for better organization or if it should be a function in the main.cpp? If the task should be in its own file how do you accept arguments in the main.cpp file and reference the other file?

Any thoughts on which method is preferred and reference material to backup the reasoning?

Best Answer

Your .cpp code files all compile into the same binary/objects, so separating files is merely a convenience for development, making code modular. After parsing the command line parameters, you may decide what calls to perform in your application.

You iterate through application arguments via the argv[] array passed to your main() entry point.

#include <iostream>

int main(int main, char* argv[])
{
        // Check the number of parameters
        if (argc < 2) {
                // Tell the user how to run the program
                std::cerr << "Usage: " << argv[0] << " NAME" << std::endl;
                /* "Usage messages" are a conventional way of telling the user
                 * how to run a program if they enter the command incorrectly.
                 */
                return 1;
        }
        // Print the user's name:
        std::cout << argv[0] << "says hello, " << argv[1] << "!" << std::endl;
        return 0;
}

As for best practices, it's best not to reinvent the wheel by using a command line parser library as answered here.