I'm trying to check if a library is available using __has_include from this post. Since I want to check each one I'm using a loop
/* Array of Strings */
const char* libraries[5] = { "iostream", "unistd.h", "stdlib.h", "Windows.h", "winaaasock2.h"};
/* Getting the length of the array */
int librariesSize = sizeof(libraries)/sizeof(libraries[0]);
/* Looping through them (5 Times) */
for (int i = 0; i < librariesSize; i ) {
#if __has_include(<\"libraries[i]"\>)
#include <\"libraries[i]"\>
cout << "Ok";
#else
cout << "Error";
#endif
}
It compiles but it's still telling me that all of them exist even for winaaasock2, which is made up from the original, winasock2.
It requires to be inside <> signs and quotes so I used back slashes
Using the same code without the loop works
#if __has_include("winaaasock2.h")
#include "winaaasock2.h"
cout << "Ok";
#else
cout << "Error";
#endif
The output here is Error, with a library like unistd.h the output is ok since it exists
What I'm missing? Thanks in advance
CodePudding user response:
It compiles
It shouldn't. The C language doesn't allow expression statements such as loops in the namespace scope. The example program is ill-formed.
Besides that, pre-processor has no knowledge of your loops. There are two possible ways that your program may be processed:
// if the header \"libraries[i]"\ exists
for (int i = 0; i < librariesSize; i ) {
// content from header \"libraries[i]"\
cout << "Ok";
}
// OR if the header \"libraries[i]"\ doesn't exist
for (int i = 0; i < librariesSize; i ) {
cout << "Error";
}
If all that you want to do is to check whether all headers exist, and produce an error otherwise, then __has_include
won't offer anything of use for you. You should simply include them. If a header is missing, there will be an error message that explains the issue.