Bash Question

C passing other c program as main argv

Just a curiosity,

Consider that I have


./first

./second


that they are executable c program

first.c:

char main(void){
return '5';
}


second.c:

#include<stdio.h>
int main(int argc, char** argv){
printf("%s", argv[2]);
return 0;
}


(I want to print 5 here)

Is it possible to compile second.c like:

gcc second.c -./first


Of course I know that wont work but is it possible to write something that will work like what I want?

Answer

The return value of main() becomes the program's exit status, which is put in the shell's $? variable. So it should be:

./first
./second $?

You should change first.c to return an int, not char; otherwise it will print the ASCII code for the '5' character, not 5.

int main(void){
    return 5;
}

And in second.c, it should be argc[1], not argv[2].

Comments