I've been programming a simple WinSock application in Visual Studio 2010. I have named my application entry point "main.c", then I came across this error while declaring a SOCKET object:
error C2275: 'SOCKET' : illegal use of this type as an expression
Oddly enough, I solved that problem by renaming the code file from main.c to main.cpp
Just out of curiosity, I want to know what is the meaning of this error, and what difference occurred by changing the extension.
Thanks in advance.
EDIT
Here is the relevant code:
#pragma comment(lib,"ws2_32")
#include <WinSock2.h>
#include <stdio.h>
int main()
{
// Startup the winsock
WORD wVersionRequested;
WSADATA wsaData;
int wsaerr;
wVersionRequested = MAKEWORD(2,2);
wsaerr = WSAStartup(wVersionRequested,&wsaData);
if(wsaerr != 0)
{
printf("Winsock2 dll is not found!\n");
WSACleanup();
return 0;
}
else
{
printf("Winsock2 dll is found!\n");
printf("Current System Status: %s.\n",wsaData.szSystemStatus);
}
//Create a SOCKET object called socketobj.
SOCKET socketobj;
socketobj = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketobj == INVALID_SOCKET)
{
printf("Socket Intialization Failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 0;
}
else
{
printf("Socket Intialization Success\n");
}
Sleep(10000);
return 0;
}
Without seeing the code it's hard to tell.
But my guess is that you have some interleaved declarations and code. MSVC's C compiler is only C89 which does not support it. That would explain why the C++ compiler accepts it, but the C compiler doesn't.
Prior to C99, all declarations must be at the start of the function or a block.
EDIT : Your code doesn't show the whole function, but you probably have some (non-declaration) code before the SOCKET socketobj;
declaration.
Now that the full function is shown, it confirms that you are interleaving declarations and code:
WORD wVersionRequested; // Declaration: ok
WSADATA wsaData; // Declaration: ok
int wsaerr; // Declaration: ok
wVersionRequested = MAKEWORD(2,2); // Code: ok
...
SOCKET socketobj; // Declaration: NOT ok
socketobj = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
The solution here is to move SOCKET socketobj;
to the start of the function with the other declarations.
There are differences between C and C++. For example, in C89 you can't declare a variable in the middle of a block of code, but only at the beginning.
Have a look at the error description: http://msdn.microsoft.com/en-us/library/76c9k4ah%28v=vs.71%29.aspx
By changing the extension to .cpp Visual Studio uses the C++ compiler instead of the C compiler (which is quite a different language).
So you probably wrote C++ code and fed it into the C compiler, which (coincidently) resulted in that error beeing thrown.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.