2012-05-21 71 views
0

我有以下代碼爲什麼VC++ 2010 Express在這個程序中不需要stdio.h但是gcC++呢?

#include <iostream> 

using namespace std; 

void WaitForEnter() 
{ 
    while(1) 
    { 
     if('\n' == getchar()) 
     { 
      break; 
     } 
    } 
    return; 
} 

int main() 
{ 
    cout<< "Press Enter to Exit... "; 
    WaitForEnter(); 
} 

這將編譯上的Microsoft Visual C++ 2010 Express和做什麼,我的預期。在使用code :: blocks和gcC++ 4.7的Ubuntu上,構建失敗,出現以下error: 'getchar' was not declared in this scope.如果我添加行​​,程序將編譯並以預期行爲運行。爲什麼此程序使用MVC++ 2010 Express進行編譯,而不使用stdio.h,但不適用於Ubuntu上使用gcC++ 4.7的code :: blocks。

+0

您是否使用預編譯頭文件(即'stdafx.h')? –

+0

@Jesse好我不熟悉預編譯頭文件,只是做了一個快速搜索,是的,我正在使用它們,我應該關閉它們嗎? – newToProgramming

+0

我不認爲visual studio會讓你編譯,除非你包括stdafx.h – Rhexis

回答

4

隨着MSVC,<stdio.h>被包括作爲包括<iostream>的副作用。查看預處理的輸出,或者按照MSVC文件中的#include路徑。

+2

-1:'iostream'不包含'stdio.h'。 –

+0

@EitanT:你檢查過了嗎?我看到了這條道路。 iostream - > istream - > ostream - > ios - > xlocnum - > cstdio - > stdio.h。 – janm

+2

這是正確的答案。 'stdafx.h'不是必需的(這可以通過直接運行'cl.exe'來輕鬆驗證)。 – jamesdlin

0

在Visual Studio中,當您創建一個新項目時,它會爲您提供stdafx.h。在這個文件中,它包括:

#include "targetver.h" 

#include <stdio.h> 
#include <tchar.h> 
+0

我爲什麼被低估? – Rhexis

2

最簡單的答案是,該標準允許任何標準頭包含任何其他頭。另一方面,如果你想編寫可移植的代碼,你不應該依賴這個,並且應該包含你的翻譯單元所需的所有頭文件。

相關問題