Redefining #ifdef _WIN32 into WINDOWS

1
2
3
4
5
6
7
8
9
10
11
12
13
//In a header accessible from everywhere:
#ifdef _WIN32
#define WINDOWS
#else
//Don't #define WINDOWS
#endif

//Elsewhere:
#ifdef WINDOWS
//_WIN32 is definitely #defined.
#else
//_WIN32 is definitely not #defined.
#endif 
The preprocessor will let you do #define WINDOWS #ifdef _WIN32 , but this will not have the effect you want. The preprocessor performs only a single pass through the code, so you'll be left with an unprocessed #ifdef in your code, that the compiler will complain about.

If you don't want to mess with macros, another alternative is to compartmentalize the implementations for each platform. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//File.h
class File{
public:
    virtual Buffer read(size_t size) = 0;
    static std::unique_ptr<File> create(const char *path);
};

//File_windows.cpp
class WindowsFile{
    HANDLE h;
public:
    WindowsFile(const char *path);
    Buffer read(size_t size) override;
};

std::unique_ptr<File> File::create(const char *path){
    return std::make_unique<WindowsFile>(path);
}

//File_unix.cpp
class UnixFile{
    FILE *f;
public:
    UnixFile(const char *path);
    Buffer read(size_t size) override;
};

std::unique_ptr<File> File::create(const char *path){
    return std::make_unique<UnixFile>(path);
}

//etc. 
(The above is just an example to make it as clear as possible. It can be done without polymorphism.)

When compiling for a given platform, you only compile the implementation for that platform, leaving out the unneeded implementations.
Why do you want to do that? This forum is here as a learning resource, for anyone who reads it. If you delete your threads, other people can't learn from them.

The only good reason to remove a thread is if you've made duplicate threads for the same question.

EDIT: And I see you've deleted your original questions from your posts. Please DON'T do that. It makes the thread useless as a learning resource for others.
Last edited on
I will never understand that. It's not like this was even a school assignment. This website isn't running out of space, you need not be concerned with that...
Last edited on
Topic archived. No new replies allowed.