1

Considering a C++ project with an include folder inside which the source code of several repositories is placed, how could I simplify their inclusion in the main file?

I tried something like this:

// config.h
#define SOMEPROJ_SRC_PATH "include/someproj/src/"
#define EXPAND_PATH(root, filepath) #root #filepath

//main.cpp
#include EXPAND_PATH(SOMEPROJ_SRC_PATH, "folder/header.h")

But it seems to not work properly.

So, what should I modify in these directives to make them work properly?

rudicangiotti
  • 566
  • 8
  • 20
  • This answer may give you some ideas: https://stackoverflow.com/a/27830271/920069 – Retired Ninja Apr 03 '22 at 15:48
  • 2
    I'm not sure how tangential it is to your question, but `'folder/header.h'` is a character literal and the compiler should be warning about that. – chris Apr 03 '22 at 15:55
  • 1
    The answer should be https://stackoverflow.com/a/71727518/7733418 but try replacing the `''` with `""` (because ... see comment by chris) and removing the two `#`. – Yunnosch Apr 03 '22 at 16:09
  • IMHO, you should specify `#include` paths on the compiler command line (or inform the compiler in another method). If the file happens to move (which it will), you will need to modify all the source files that include it. – Thomas Matthews Apr 03 '22 at 18:05

2 Answers2

2

The right way to do it is to pass SOMEPROJ_SRC_PATH as a search path of include files with -I option.

main.cpp:

#include <iostream>

#include "some.h"

int main() {
    std::cout << HELLO << std::endl;
}

/some/path/some.h:

#define HELLO "Hello, world!"

And then compile it:

g++ -I /some/path -o main main.cpp 
1

First fix the problem pointed out in the comment by chris.
I.e. replace the '' with "".

Then remove the surplus "stringifying" #s.

#include <stdio.h>
#define SOMEPROJ_SRC_PATH "include/someproj/src/"
#define EXPAND_PATH(root, filepath) root filepath

int main(void)
{
    printf(EXPAND_PATH(SOMEPROJ_SRC_PATH, "Hello World"));

    return 0;
}

This macro expands to "include/someproj/src/" "Hello World", which is per normal string handling mechanisms concatenated, so that the output is

include/someproj/src/Hello World

But really, read up on what https://stackoverflow.com/a/71727518/7733418 (other answer here) proposes, I support that alternative approach.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54