Paul Harrison
Paul Harrison

Reputation: 83

Concatenating preprocessor definition and string to create #include path

I am trying to concatenate a file path for a header file using a preprocessor definition (in this case, the project path) and the filename, but I am persistently getting the following: "warning C4067: unexpected tokens following preprocessor directive - expected a newline". I have tried the following approaches:

#define RESOURCE_PATH PROJECT_DIRECTORY "resource.h"
#include RESOURCE_PATH

and:

#define RESOURCE_FILE "resource.h"
#define RESOURCE_PATH PROJECT_DIRECTORY RESOURCE_FILE
#include RESOURCE_PATH

Both of yield warning C4067 on the #include line. I have also tried:

#define RESOURCE_FILE "resource.h"
#define RESOURCE_PATH PROJECT_DIRECTORY ## RESOURCE_FILE
#include RESOURCE_PATH

which also does not work but changes the error to "error C2006: '#include': expected a filename, found 'identifier'".

I have double checked that my source file is UTF-8, so I'm not inadvertently including Unicode characters. PROJECT_DIRECTORY appears to be properly formatted and is the correct path.

I'm using VS2015.

Any ideas would be appreciated!

Upvotes: 3

Views: 1252

Answers (1)

SU3
SU3

Reputation: 5409

There are two things that are causing your problem.

  1. You are trying to turn "A" "B" into "AB".
  2. #include "A""B" is not valid syntax.

What you can do, is concatenate A and B and then turn that into a string literal.

#define STR_IMPL(A) #A
#define STR(A) STR_IMPL(A)

Then you can do this:

#define RESOURCE_FILE resource.h
#define PROJECT_DIRECTORY /foo/bar
#define RESOURCE_PATH STR(PROJECT_DIRECTORY/RESOURCE_FILE)

#include RESOURCE_PATH

Unfortunately, there's no way to turn "A" into A or "A""B" into "AB" in C++ preprocessor. So, you have to work with tokens without quotes and stringize the result at the end.

Upvotes: 4

Related Questions