Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

command line arguments to execute a C++ program

this is the main of my c++ program:

void main(int argc, char** argv, Arguments& arguments)

the first arguments is a file and the rest are boolean values.
I was wondering what is the correct syntax for the command line to compile the program.
I tried:

gcc  -o "argument1" "argument2" "argument3" prog.cpp  

and

g++ -std=c++11 -o "argument1" "argument2" "argument3" prog.cpp

but I get this error:

linker command failed with exit code 1 (use -v to see invocation)

I am doubting that I am not passing the arguments correctly and therefore my program doesn't link to the input file (argument1) correctly.
thank you for correcting me.


1 Answers

Main and Command Line Arguments

Main can have one of two forms:

int main()
int main(int argc, char** argv)

In the first form, you cannot pass any arguments. In the second form argc is a count of the arguments passed on the command line, and argv is an array of char* (c-style strings) of length argc containing the command line arguments.

So, for example, if you called your program as

./program apple bananna carrot date

Then argc would be equal to 5 and argv would contain the following values:

argv[0] = "./program" -- the name of your program as called on the command line. 
argv[1] = "apple"
argv[2] = "bananna"
argv[3] = "carrot"
argv[4] = "date"

Compiling and Running your Program

C++ is not an interpreted language and must therefore be compiled. Assuming you have your source code in a file called program.cpp, and you want your executable to be called program, then you would invoke g++ as follows:

g++ -o program program.cpp

If you ls the current directory, you should now see a file called program in the directory beside your source code. You can now run this program (again, assuming you named the output file program)

./program arg1 arg2 arg3

and the strings arg1, arg2, and arg3 will be passed into main as described above.

like image 161
Paul Belanger Avatar answered Mar 15 '26 21:03

Paul Belanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!