What is the difference between _tmain() and main() in C++?

后端 未结 5 1162
悲哀的现实
悲哀的现实 2020-11-22 10:37

If I run my C++ application with the following main() method everything is OK:

int main(int argc, char *argv[]) 
{
   cout << \"There are \" << a         


        
5条回答
  •  难免孤独
    2020-11-22 10:54

    _tmain is a macro that gets redefined depending on whether or not you compile with Unicode or ASCII. It is a Microsoft extension and isn't guaranteed to work on any other compilers.

    The correct declaration is

     int _tmain(int argc, _TCHAR *argv[]) 
    

    If the macro UNICODE is defined, that expands to

    int wmain(int argc, wchar_t *argv[])
    

    Otherwise it expands to

    int main(int argc, char *argv[])
    

    Your definition goes for a bit of each, and (if you have UNICODE defined) will expand to

     int wmain(int argc, char *argv[])
    

    which is just plain wrong.

    std::cout works with ASCII characters. You need std::wcout if you are using wide characters.

    try something like this

    #include 
    #include 
    
    #if defined(UNICODE)
        #define _tcout std::wcout
    #else
        #define _tcout std::cout
    #endif
    
    int _tmain(int argc, _TCHAR *argv[]) 
    {
       _tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;
    
       // Loop through each argument and print its number and value
       for (int i=0; i

    Or you could just decide in advance whether to use wide or narrow characters. :-)

    Updated 12 Nov 2013:

    Changed the traditional "TCHAR" to "_TCHAR" which seems to be the latest fashion. Both work fine.

    End Update

提交回复
热议问题