库包含具有相同标题名称的路径

2022-01-25 00:00:00 include include-path c++

What is the best method to include a file that has same name in another folder from additional include directories?

Example:

lib1/include/foo.h
lib2/include/foo.h

where both lib1/include and lib2/include are added in additional include directories.

Edit:

The libs are from different SDK's and every developer installs them in his own place. Only thing that is sure is that both folders are in IDE's additional include paths

method 1:

#include "../../lib1/include/foo.h

method2:

Add lib1/include before lib2/include in search paths and because they are searched in order with:

#include "foo.h"

lib1/include/foo.h will be included

解决方案

First off, this answer assumes that the include guards for the two headers are compatible (i.e. not the same symbols).

One thing you can do is create links in known locations to the header files of interest, giving the links themselves distinct names. For example, say your two libraries are installed at $LIB1PATH and $LIB2PATH, which could have different values in different build environments. Thus the headers you want to get are at $LIB1PATH/include/foo.h and $LIB2PATH/include/foo.h.

You could go two ways with this. One is by creating direct links. This could look like this in your project's directory tree:

$PROJDIR/
    include/
    lib_include/
        lib1_foo.h -> $LIB1PATH/include/foo.h
        lib2_foo.h -> $LIB2PATH/include/foo.h
    src/

This could get tricky if your code is in a repository, because you couldn't check these links in; they'd be wrong in other environments. Also, if you have a lot of these links and few libraries, you'd have to recreate all of them whenever lib1 or lib2 move... not cool. You can get around this problem by creating links in the directory that contains the project's directory:

$PROJDIR/
    include/
    lib_include/
        lib1_foo.h -> ../../lib1/include/foo.h
        lib2_foo.h -> ../../lib2/include/foo.h
    src/
lib1 -> $LIB1PATH/
lib2 -> $LIB2PATH/

In both cases, you need to make sure $PROJDIR/lib_include is on your include path. Also, you only need to have $LIB1PATH/include and $LIB2PATH/include in your include path if the two foo.h headers pull in more headers from those directories. You could also put the links in include and get rid of lib_include, but I like keeping these things separate.

相关文章