Home > Net >  Simplify C inclusion with macros
Simplify C inclusion with macros

Time:04-04

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?

CodePudding user response:

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 

CodePudding user response:

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.

  • Related