in header file I have defined the following function
#ifndef OS_H
#define OS_H
#include <string>
#include <vector>
int GetDirectoryFiles(std::string directory, std::vector<std::string> &files);
#endif /* OS_H */
I would like have separate implementations for each platform
#include "os.h"
#include <iostream>
#ifdef OSWIN
#include <windows.h>
#elif OSLINUX
#include <dirent.h>
#endif
int GetDirectoryFiles(std::string directory, std::vector<std::string> &files)
#ifdef OSLINUX
{
DIR *dp;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
files.push_back(string(dirp->d_name));
}
closedir(dp);
return 0;
}
#elif OSWIN
{
std::clog << "entered!" << std::endl;
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(directory.c_str(), &FindFileData);
if ( hFind == INVALID_HANDLE_VALUE )
return -1;
do {
files.push_back(FindFileData.cFileName);
} while(FindNextFile(hFind, &FindFileData) != 0);
FindClose( hFind );
return 0;
}
#endif
Is there more elegant way to do this (what is considered good style).
The typical way to handle this would be to have the function declaration in a shared header file, then have one cpp file per platform that contains the different platform-specific definitions of this function. Your build system then only makes and links in the corresponding platform-specific cpp file.
ie
Filesystem.h
Filesystem_Windows.cpp:
Filesystem_Linux.cpp:
See the source tree of Qt, which is a very popular cross-platform C++ library, as an example of this kind of structure.