How to avoid relative paths in include folder

2019-08-02 03:34发布

问题:

Within Android Studio, I have a directory structure like so:

App
├── CMakeLists.txt
└── src
    ├── foo
    │   ├── CMakeLists.txt
    │   ├── foo.cpp
    │   └── foo.h
    ├── main
    │   └── cpp
    │       ├── CMakeLists.txt
    │       └── main.cpp
    └── test
        ├── CMakeLists.txt
        └── testDriver.cpp

In main.cpp, I would like to #include "foo.h" or even #include "fooLib/foo.h" but It won't compile unless I #include "../../fooLib/foo.h". I am trying to configure CMake within android studio to allow me to use the former. I tried export, target_include_dirs, but there is something i am just not getting.

I would like to be able to refer to "fooLib/foo" from anywhere.

回答1:

Inside App/CMakeLists.txt

# set the root directory as ${CMAKE_CURRENT_SOURCE_DIR} which is a
# CMAKE build-in function to return the current dir where your CMakeLists.txt is. 
# Specifically, it is "<your-path>/App/"
set(APP_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR})

# set your 3 other root dirs, i.e. foo, main and test under app/src.
set(APP_ROOT_SRC_DIR ${APP_ROOT_DIR}/src)
set(APP_ROOT_FOO_DIR ${APP_ROOT_SRC_DIR}/foo)
set(APP_ROOT_MAIN_DIR ${APP_ROOT_SRC_DIR}/main)
set(APP_ROOT_TEST_DIR ${APP_ROOT_SRC_DIR}/test)

# set your include paths into "SHARED_INCLUDES" variable.
set(SHARED_INCLUDES
                ${APP_ROOT_FOO_DIR}
                # ${APP_ROOT_FOO_DIR}/<your-other-child-dirs>

                ${APP_ROOT_MAIN_DIR}
                ${APP_ROOT_MAIN_DIR}/cpp
                # ${APP_ROOT_MAIN_DIR}/<your-other-child-dirs>

                ${APP_ROOT_TEST_DIR}
                # ${APP_ROOT_TEST_DIR}/<your-other-child-dirs>
                )

# This function will have effect to all the downstream cmakelist files. 
include_directories(${SHARED_INCLUDES})


# remember to include downstream cmakelist files for foo, main and test.
add_subdirectory(${APP_ROOT_FOO_DIR} bin-dir)
add_subdirectory(${APP_ROOT_MAIN_DIR} bin-dir)
add_subdirectory(${APP_ROOT_TEST_DIR} bin-dir)

Now, you can use the #include "foo.h" anywhere without quoting its relative path.



回答2:

The fix is to place include_directories(src) within App/CMakeLists.txt