0

if my C program doesn't print out anything, it just returns a value, how can I use gcc to check what value my program returns? For example,

gcc test.c

after this I get a a.out, however, if I type "a", nothing will show since my test.c doesn't print anything it just return a value, so how can I check what value my test.c returns?

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • 3
    Operating system? Shell? – genpfault Oct 16 '20 at 15:45
  • If you type `a`, I would expect you to get something along the lines of `a: command not found`. `a` is not the same as `a.out`. If you want to know the value returned by main when your program executes from a shell, inspect `$?` – William Pursell Oct 16 '20 at 15:46
  • In Windows: see https://www.shellhacks.com/windows-get-exit-code-errorlevel-cmd-powershell/ ... in bash (and possibly other Un*x shells): `echo $?` – pmg Oct 16 '20 at 15:46
  • `%ERRORLEVEL%` on windows command prompt. – MikeCAT Oct 16 '20 at 15:47

1 Answers1

2

If you are using a typical Linux shell like bash, the exit code from a program (which is what main returns) is stored in the $? built-in variable. So if your program returns 42, you can do:

$ ./a.out
$ echo $?
42

Note that this is 8 bits. It can store a number from 0 to 255. Bigger numbers will wrap around.

On Windows, the variable is called %ERRORLEVEL% (not case-sensitive):

C:\> a.exe
C:\> echo %errorlevel%
42
user253751
  • 57,427
  • 7
  • 48
  • 90