I would like to ask if it is possible to use the entities defined in #ifdef block in header files. To be clear, I have following code:
#ifdef WIN32
#include <winsock2.h>
#define SOCKET_HANDLE SOCKET
#define CONNECTION_HANDLE SOCKET
#endif
SOCKET_HANDLE createServerSocket(const char* hostAddress, short port);
I am Java developer and this seems completely fine for me. However compiler has a problem with this.
Can you explain why is that code a problem?
Also how can I force to compile it. (The idea is to have generic interface and conditional compilation to determine real types according to running platform at compile time.)
Thanks
#ifdefis an conditional preprocessor statement. Much likeifstatements they need something to evaluate so one branch or another can be taken.In the case of
#ifdef, it is evaluating whether or not the given macro is defined. e.g.Checks to see if the BLAH macro is defined. Based on the result the code in either the true or false branch is included and compiled, the others discarded.
In your particular case, the usage of
#ifdefis quite clearly to ensure the headers and socket types appropriate to operating system compiling the code is used (ignoring for the moment cross compiling).For the code in your question, you want to check for the macro
_WIN32and/or_WIN64. These are implicitly defined by most compilers targeting the Windows operating system. Note that in VC++_WIN32is defined for 32bit and 64bit Windows, while_WIN64is only defined for 64bit Windows. See this discussion for more details.Edit
Having noticed your changes to the question and the exact error message you posted in a comment, the problem is trifold:
WIN32is the wrong macro. It should be_WIN32or_WIN64. See above.#defines and#includeis never seen by the compiler, and thusSOCKET_HANDLEandCONNECTION_HANDLEare both undefined.SOCKET_HANDLE createServerSocket(const char* hostAddress, short port);it doesn’t recogniseSOCKET_HANDLEand exits with an errorThe solution is to fix the macro you are checking, changing it from
WIN32to_WIN32or_WIN64. Further you should provide an#elsebranch in the event operating system detection completely fails, e.g. assume you are compiling on$mostlikelyosand#defineand#includeappropriately.