Skip to content

Example: Using csv‐parser with CMake and FetchContent

Vincent La edited this page May 18, 2024 · 5 revisions

This is a basic example of using CMake's FetchContent module to add csv-parser as a dependency.

This provides a simple way to integrate csv-parser into your project without having to copy and paste the single header version or using git submodules.

CMakeLists.txt

# CMakeList.txt : CMake project for my-project, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)
include(FetchContent)

project ("my-project")

# Add source to this project's executable.
add_executable (my-executable "main.cpp")

if (CMAKE_VERSION VERSION_GREATER 3.12)
  set_property(TARGET my-executable PROPERTY CXX_STANDARD 20)
endif()

# Fetch csv-parser and make it available to my-executable
FetchContent_Declare(
  csv  
  GIT_REPOSITORY https://github.com/vincentlaucsb/csv-parser.git
  GIT_SHALLOW TRUE 
  GIT_TAG 2.2.1
) 

FetchContent_MakeAvailable(csv)

target_include_directories(my-executable PRIVATE csv)
target_link_libraries(my-executable csv)

main.cpp

// main.cpp : Defines the entry point for the application.
//

#include "csv.hpp"

# using namespace csv;
using csv::operator ""_csv;
using namespace std;

int main()
{
    auto rows = "Actor,Character\r\n"
        "Will Ferrell,Ricky Bobby\r\n"
        "John C. Reilly,Cal Naughton Jr.\r\n"
        "Sacha Baron Cohen,Jean Giard\r\n"_csv;

    for (auto& row : rows) {
        std::cout << row[1].get_sv() << " played by " << row[0].get_sv() << std::endl;
    }
	
    return 0;
}

Example Output

image

Clone this wiki locally