Issue
I cloned the SDL_image
library and wish to build it using a simple add_subdirectory(...)
command. My current directory structure is as follows.
├───lib
│ ├───sdl_image
| ├─── ...
├───build
I have a CMakeLists.txt
which is as follows.
cmake_minimum_required(VERSION 3.13)
project(test)
add_subdirectory(lib/sdl_image)
Upon execution (For my environment, cmake . -G "MinGW Makefiles"
), I get the following error.
CMake Error at lib/sdl_image/CMakeLists.txt:18 (message):
Prevented in-tree built. Please create a build directory outside of the
SDL_image source code and call cmake from there
In an attempt to fix this, I modified my CMakeLists.txt
add_subdirectory(...)
command as follows. If I understand correctly, this should specify the output directory to build/sdl_image
, outside of the SDL_image
source code.
...
add_subdirectory(lib/sdl_image build/sdl_image)
However, I still get the same error. The line that is giving me the error under lib/sdl_image/CMakeLists.txt
is as follows.
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR)
message(FATAL_ERROR ...)
endif()
I don't understand why this condition is getting triggered since I've specified the source_dir
and binary_dir
(parameters in add_subdirectory(...)
) as very different paths. I also tried add_subdirectory(lib/sdl_image ../../build/sdl_image)
in case it was treated as relative to the source_dir
. This is still not working.
Any help is appreciated. Thanks.
Solution
This is about building in sources (calling cmake in your sources), not a path problem where to put sdl_image.
You probably call cmake from within your source directory which is considered a bad practice (same thing when using autotools, or any other build generator).
So you should have some kind of build tree like:
MyProjectWorkspace
|
\_ sources (tree in your case)
\_ build
and invoke cake with cmake ../build
from the build directory.
The reason is that when building in sources, you somehow "pollute" your sources. Very likely you will need to add some .gitignore (if using git) and take special care not to commit thing that are built.
Moreover, when generating code, the generated code will appear in the source tree leading to some confusions at some point (you edit the generated file and see it deleted later).
It is also handy: to completely clear a build, you only need to remove the content of the build directory (would be much harder within the sources)
Last but not least, this also ease the packager's job as usually, the use off source builds.
Answered By - OznOg Answer Checked By - Terry (WPSolving Volunteer)