implicit declaration of function 'getch'

You get the warning

implicit declaration of function 'getch'

because you have not include any header that declares getch. No such function is declared in the standard headers <stdio.h> or <stdlib.h>.

In fact, there is no function named getch in any standard C header.

Prior to the C99 standard, the C language permitted calls to functions with no visible declaration. Such a call would in effect create an implicit declaration of a function returning int and taking arguments of whatever (promoted) type you actually passed.

Depending on this has never been a good idea. You should always have a proper #include directive for the header that declares any library function you use in your program.

C99 dropped the "implicit int" rule and made any call to a function with no visible declaration a constraint violation, requiring a diagnostic (That diagnostic is permitted to be a non-fatal error.)

If you're compiling on Windows, if I recall correctly, there's a getch() function declared in <conio.h>. If you want to use that function, you need to add #include <conio.h> to your program.

I do not recommend doing this; using getch() is unnecessary and makes your program non-portable. Some Windows development environments make it difficult to run "console programs" (programs that print to standard output rather than creating a GUI); often running such a program creates a temporary window that's destroyed as soon as the program finishes. Calling the standard getchar() function is another way to keep the window from vanishing. Or you can execute the program from a command prompt, and its output will appear in your current command window.

If you're compiling on a UNIX-like system, there's another function called getch(), declared in <curses.h>. I can compile and execute your program on Linux if I add -lcurses to the compiler command line. But you shouldn't use that getch() function if you haven't first set up the curses environment, and it's fairly clear you don't want to do that.

Ideally, the classic "hello world" program should be just:

#include <stdio.h>
int main(void) {
    printf("Hello world!\n");
    return 0;
}

How you get that to run and let you see the output depends on your environment (which you haven't told us about).


For linux, use this code:

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getch (void)
{
        int ch;
        struct termios oldt, newt;

        tcgetattr(STDIN_FILENO, &oldt);
        newt = oldt;
        newt.c_lflag &= ~(ICANON|ECHO);
        tcsetattr(STDIN_FILENO, TCSANOW, &newt);
        ch = getchar();
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

        return ch;
}

For Windows, add this line:

#include <conio.h>

Tags:

C