Different mains
Basic main
Function:
#include <stdio.h>
int main() {
// Program logic goes here
return 0;
}
Explanation:
This is the simplest form of the
main
function.It does not accept any command-line arguments.
The program logic is placed within the curly braces.
It returns an integer value (0 in this case) to the operating system, indicating successful execution.
Below are examples of main
function signatures that use argc
, argv
, and envp
, along with sample code that demonstrates their usage. I'll also provide comments explaining each part of the code and show how to execute the program in a Bash environment, passing command-line arguments and setting environment variables.
1. main
Function with argc
and argv
:
#include <stdio.h>
int main(int argc, char *argv[]) {
// argc: Number of command-line arguments
// argv: Array of command-line argument strings
// Check if at least two command-line arguments are provided
if (argc < 3) {
printf("Usage: %s <arg1> <arg2>\n", argv[0]);
return 1; // Return 1 to indicate an error
}
// Access command-line arguments
printf("First argument: %s\n", argv[1]);
printf("Second argument: %s\n", argv[2]);
return 0;
}
Execution and Output in Bash:
$ gcc command_line_args.c -o command_line_args
$ ./command_line_args arg1_value arg2_value
First argument: arg1_value
Second argument: arg2_value
2. main
Function with argc
, argv
, and envp
:
#include <stdio.h>
int main(int argc, char *argv[], char *envp[]) {
// argc: Number of command-line arguments
// argv: Array of command-line argument strings
// envp: Array of environment variable strings
// Access command-line arguments
printf("Command-line arguments:\n");
for (int i = 0; i < argc; ++i) {
printf(" %s\n", argv[i]);
}
// Access environment variables
printf("\nEnvironment variables:\n");
for (int i = 0; envp[i] != NULL; ++i) {
printf(" %s\n", envp[i]);
}
return 0;
}
Execution and Output in Bash:
$ gcc env_args.c -o env_args
$ ./env_args arg1 arg2
Command-line arguments:
./env_args
arg1
arg2
Environment variables:
PATH=...
HOME=...
...
$ MY_ENV_VAR=123 ./env_args arg1 arg2
Command-line arguments:
./env_args
arg1
arg2
Environment variables:
PATH=...
HOME=...
...
MY_ENV_VAR=123
These examples demonstrate how to use argc
, argv
, and envp
in a C program, and the Bash commands show how to compile and execute the programs while providing command-line arguments and setting environment variables.