C++ how to use *.dylib

chuuuing
2 min readApr 9, 2021

Environment: macOS
C++ Standard: 17
IDE: CLion

This tutorial will use DuckDB as example. From their installation page I downloaded the zip file which includes the follows:

1. Put files under my project

Put the folder under [myproject]/dependencies. Here myproject=duckdb-test.

2. Configurate CMakeLists.txt

  • include_directories() searches for *.h file
  • link_directories() searches for *.dylib file
  • target_link_libraries() add the external library. The name convention of *.dylib file is “lb”+[name of library] + “.dylib”, we take the [name of library] and use it as the second parameter for the target_link_libraries() function
cmake_minimum_required(VERSION 3.17)
project(duckdb-test)

set(CMAKE_CXX_STANDARD 17)

include_directories(${CMAKE_SOURCE_DIR}/dependencies/libduckdb-osx-amd64)
link_directories(${CMAKE_SOURCE_DIR}/dependencies/libduckdb-osx-amd64)

add_executable(duckdb-test main.cpp)

target_link_libraries(duckdb-test duckdb)

3. Now try it out in main.cpp

#include "duckdb.hpp"
#include <iostream>

using namespace duckdb;

int main(){
DuckDB db(nullptr);
Connection con(db);

con.Query("CREATE TABLE integers(i INTEGER, j INTEGER)");
con.Query("INSERT INTO integers VALUES (3, 4), (5, 6), (7, NULL)");

auto result = con.Query("SELECT * FROM integers");
result->Print();
}

Get the output:

i j 
INTEGER INTEGER
[ Rows: 3]
3 4
5 6
7 NULL

4. Problem of unverified developer

You might encounter this problem. Solve it by changing the setting in Security & Privacy.

--

--