Why does mingw-gcc allow getch() to be used unconditionally?

时间:2016-02-03 04:07:31

标签: c linux windows gcc

I recently started porting a TON of my C programs to a Windows environment, from my previous Linux development PC. I noticed something a bit off about mingw's Windows GCC implementation.

In Windows, I found a lovely function called getch. It's easy, it's immediate... and it's also non-standard.

I'd like to focus of the "non-standard" part of it. Specifically, I want to know why mingw-gcc allows me to use it, without using anything but the standard libraries.

Assume we have a program that prints "Hello, World!", a NL and CR, and then waits for a key and a return:

#include <stdio.h>
int main(void)
{
    char str[14] = "Hello, World!"; //13 characters and a terminator
    printf("%s\n\r", str);
    scanf("%c");
    return 0;
}

Now, let's change a bit of that program to use getch:

#include <stdio.h>
int main(void)
{
    char str[14] = "Hello, World!"; //Again, 13 characters and a terminator
    printf("%s\n\r", str);
    getch(); //See? now it uses getch.
    return 0;
}

The interesting part is, Isn't getch a call made by the conio.h library for old DOS/Win32 environments? The compiler doesn't even give a warning. Why does this work?

Here's something I find even a bit more unsettling:

int main(void) //literally NOTHING included
{
    getch();
    return 0;
}

What on earth? I know for a fact that getch does not exist on Linux environments (natively, anyways). So, where is the compiler getting this call from?

My best guess (please correct me if I am wrong) is that the decision to link whatever has getch is made at link time, not compile time.

In any case, this seems a little odd to me. Why does an implementation of GCC automatically include clearly non-standard capability on Windows?

2 个答案:

答案 0 :(得分:1)

编译步骤有效(虽然它应该产生警告),因为传统上,C允许你调用那些尚未声明的函数,provided that they return an int getch()。

链接步骤有效,因为MinGW使用的C运行时库是单个库,即它提供所有Visual C运行时库函数,包括非标准库函数。 MinGW可能默认与它链接,因为(除了非常罕见的边缘情况)它总是需要的,即使你想要的只是一个什么都不做的main()函数。 : - )

还应该提到的是,有问题的库并没有正式支持第三方使用,除了在Visual Studio 6中构建的应用程序。更现代的运行时已弃用getch以支持等效但符合标准_getch,但VS6早于这种变化。

答案 1 :(得分:-1)

编译步骤可能会“起作用”,因为编译器(至少旧版本的编译器 - 我们知道Visual Studio不是最新的C标准)会假设返回类型和参数都是{{1 }}

链接步骤需要链接相应的库。