Compiling SQLite3 with C++

Advertisement

Advertisement

Introduction

If you want to write a C++ program that utilizes Sqlite3 you will need to take an extra step in the compile and link process in order to compile Sqlite3 with the C compiler (gcc), and then your C++ program with the C++ compiler (g++) If you try to compile Sqlite3 with g++ it will error.

For this example, I am using g++ and gcc to compile. I tested this in Windows 10 with MinGW64, but it should also work in Linux and Mac.

If you want to learn more about using SQLite3, check out my other tutorials:

Install Mingw

I am using the 64-bit version of MinGW downloaded from http://mingw-w64.org/doku.php/download/mingw-builds which links to a Sourceforge download.

After installing, add the MinGW bin directory to your PATH environment variable. For example:

C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin

This will put gcc and g++ in your PATH.

Obtain Sqlite3 source code

Download Sqlite3 source code from https://www.sqlite.org/download.html.

Download the file labeled amalgamation (e.g. https://www.sqlite.org/2019/sqlite-amalgamation-3300100.zip) and then extract the zip file. It will contain some .c and .h files.

To compile Sqlite3 by itself as the standalone executable application, run:

# This will generate the executable sqlite3 with the shell
gcc sqlite3.c shell.c -o sqlite3

To compile the object file so you can later link it with a C++ program compiled using g++, first compile only to get the object file:

# Will generate sqlite3.o (-c is compile only, generating object file)
gcc sqlite3.c -c

Then compile your .cpp file with g++, linking it to the sqlite3.o file. Here is an example C++ file that will output the SQLite version and create an empty database file.

// main.cpp
#include <sqlite3.h>
#include <iostream>

int main()
{
    std::cout << "Sqlite version: " << sqlite3_libversion() << std::endl;

    sqlite3* mydb;
    std::cout << sqlite3_open("test.db", &mydb) << std::endl;
    std::cout << "Database file:" << mydb << std::endl;
    std::cout << sqlite3_close(mydb);

    return 0;
}

Learn more about the API and what functions are available at https://www.sqlite.org/c3ref/intro.html or look inside the sqlite3.h file.

Once you have the sqlite3.o object file to link against (statically), and you have your main.cpp file, you can compile and link with the following command:

# Compile main.cpp, link with sqlite3.o, and specify the include path for sqlite3.h
g++ main.cpp sqlite3.o -Ipath\to\sqlite3

Be sure to set the include directory with -I so it knows where to find the sqlite3.h file.

After compiling and linking you should have an a.exe that will print out the SQLite version and generate the empty database file.

Conclusion

After following these steps you should be able to compile a C++ application that uses the C library SQLite3 using gcc and g++.

References

Advertisement

Advertisement