Practical Implementation
graph TD
A[Design Phase] --> B[Platform Detection]
A --> C[Interface Definition]
B --> D[Conditional Compilation]
C --> E[Implementation Strategy]
#ifndef CROSS_PLATFORM_FS_H
#define CROSS_PLATFORM_FS_H
#include <string>
#include <vector>
class CrossPlatformFileSystem {
public:
// Platform-independent interface
static bool createDirectory(const std::string& path);
static bool removeDirectory(const std::string& path);
static std::vector<std::string> listFiles(const std::string& directory);
private:
// Platform-specific implementation details
#ifdef __linux__
static bool linuxCreateDirectory(const std::string& path);
#elif defined(_WIN32)
static bool windowsCreateDirectory(const std::string& path);
#endif
};
#endif // CROSS_PLATFORM_FS_H
#include "CrossPlatformFS.h"
#ifdef __linux__
#include <sys/stat.h>
#include <dirent.h>
#elif defined(_WIN32)
#include <windows.h>
#endif
bool CrossPlatformFileSystem::createDirectory(const std::string& path) {
#ifdef __linux__
return linuxCreateDirectory(path);
#elif defined(_WIN32)
return windowsCreateDirectory(path);
#else
#error Unsupported platform
#endif
}
#ifdef __linux__
bool CrossPlatformFileSystem::linuxCreateDirectory(const std::string& path) {
return mkdir(path.c_str(), 0755) == 0;
}
#endif
#ifdef _WIN32
bool CrossPlatformFileSystem::windowsCreateDirectory(const std::string& path) {
return CreateDirectoryA(path.c_str(), NULL) != 0;
}
#endif
Compilation Strategies
Platform |
Compilation Command |
Key Flags |
Linux |
g++ -std=c++17 -O2 |
-pthread |
Windows |
cl /std:c++17 /O2 |
/EHsc |
macOS |
clang++ -std=c++17 |
-stdlib=libc++ |
Error Handling and Logging
class PlatformLogger {
public:
static void log(const std::string& message) {
#ifdef __linux__
// Linux-specific logging
syslog(LOG_INFO, "%s", message.c_str());
#elif defined(_WIN32)
// Windows-specific logging
OutputDebugStringA(message.c_str());
#endif
}
};
Recommended Techniques
graph LR
A[Cross-Platform Development] --> B[Minimal Platform-Specific Code]
A --> C[Standard C++ Features]
A --> D[Abstraction Layers]
A --> E[Comprehensive Testing]
LabEx Recommendations
At LabEx, we emphasize:
- Using standard C++ libraries
- Implementing portable abstractions
- Rigorous cross-platform testing
- Minimizing platform-specific code
Compilation and Testing
Sample Compilation Script
#!/bin/bash
## Cross-platform compilation script
## Linux compilation
g++ -std=c++17 -O2 main.cpp CrossPlatformFS.cpp -o app_linux
## Windows cross-compilation (using mingw)
x86_64-w64-mingw32-g++ -std=c++17 -O2 main.cpp CrossPlatformFS.cpp -o app_windows.exe