Monday, August 15, 2016

Use CMake to develop an SQLite Visual Studio C++ application

I wanted to write a Windows 64 bit C++ executable that makes use of a SQLite database using CMake to generate a Visual Studio solution.

Prepare SQLite

  1. The simplest way to use SQLite in my code is to download and use the amalgamated source files and binaries from the SQLite website https://www.sqlite.org/download.html.
  2. Extract the amalgamated SQLite source files into a folder e.g. c:\path\to\sqlite\include\.


  3. Extract the compiled SQLite binaries into a folder e.g. c:\path\to\sqlite\lib\.

  4. In order to link the SQLite dll into a C++ executable, the dll needs to have a exported library. This can be done by opening a Visual Studio Command Prompt. Select Start | Visual Studio 2015 | VS2015 x64 Native Tools Command Prompt.
  5. In the Command Prompt, change directory to the location of the SQLite binaries e.g. C:\path\to\sqlite\lib\. Type in the LIB command:

    C:\> LIB /def:sqlite3.def


    The files sqlite3.lib and sqlite3.exp are generated.

Create your application's CMakeLists.txt
  1. In your C++ application's root folder e.g. C:\path\to\sqliteexample\, use a text editor to create a CMakeLists.txt file.

  2. In the CMakeLists.txt, define the SQLite library name and locations of the headers and library, as shown below.
An example CMakeLists.txt

cmake_minimum_required(VERSION 2.8.6)
project(sqliteexample)

# compile all *.cpp files
file (GLOB SOURCES "src/*.cpp")

# define libraries to link to final executable
set (PROJECT_LINK_LIBS sqlite3.dll)

# define the sqlite header include file directory
set (SQLITE_INCLUDE ../sqlite/include)

# define the sqlite link library directory
set (SQLITE_LINK_DIR ../sqlite/lib)

# define the directories to search for libraries
link_directories ( ${SQLITE_LINK_DIR})

# define the directories to search for headers
include_directories (include ${SQLITE_INCLUDE})

# define the final executable
add_executable(sqliteexample ${SOURCES})

# define the libraries to link to the final executable
target_link_libraries (sqliteexample ${PROJECT_LINK_LIBS})


Generate the Visual Studio solution files

  1. Write the C++ source code e.g. main.cpp in the C++ application source folder e.g. C:\path\to\sqliteexample\src\.
  2. Create a build folder underneath the C++ application root folder e.g. C:\path\to\sqliteexample\.
  3. Open up the Visual Studio x64 Command Prompt. Change directory to the build folder, e.g. C:\path\to\sqliteexample\build\.
  4. In the Command Prompt, type in the cmake command:

    C:\> cmake -G "Visual Studio 14 2015 Win64" ..


    The Visual Studio solution files are generated.

  5. Next, open up the generated Visual Studio solution e.g. sqliteexample.sln in Visual Studio.
  6. Select Build | Build Solution to compile your SQLite C++ application.

No comments: