Search code examples
ccsvcmakeinclude-path

Include Directory to CSV File Cmake


I am attempting to use cmake to build my visual studio 2017 project. The program, written in C, parses a csv file. The issue is the file is in a different folder from the c file. How would I set it so I can use fopen() just by giving it the name of the file rather than the path?

This is the layout of my program:

|--include
|   |--header_files.h
|--src
|   |--util
|   |   |--app_util.c
|   |   |--other_files.c
|   |--main
|   |   |--app.c
|--userdata
|   |--fitness_cases.csv
|--CMakeLists.txt

The goal is to be able to call fopen("fitness_cases.csv") in app_util.c, which I think should be done by including the directory /userdata in the CMakeLists.txt file. How would I do this?


Solution

  • I figured it out, but I ended up doing something slightly different than what my question asked. I came up with a solution that automatically detects the path of the file and includes it as a macro in a header file.

    The way I did it was by creating a CMakeLists.txt file in the include folder. I then had it configure a header file which contained a macro to the path by searching for the csv file is userdata. Then I included the new CMakeLists.txt in the main one.

    This was the setup my program has:

    |--include
    |   |--header_files.h
    |   |--CMakeLists.txt
    |   |--csv_file.h.in
    |--src
    |   |--util
    |   |   |--app_util.c
    |   |   |--other_files.c
    |   |--main
    |   |   |--app.c
    |--userdata
    |   |--fitness_cases.csv
    |--CMakeLists.txt
    

    The CMakeLists.txt file in the include folder looks like this:

    #Search for csv file
    file(GLOB CSV_DIR "data/*.csv" )
    
    # configure the header.
    set(DIR_STRING "${CSV_DIR}")
    configure_file("include/params.h.in" "include/params.h")
    
    # Includes the new header
    include_directories(${CMAKE_CURRENT_BINARY_DIR})
    

    csv_file.h.in is just a single line:

    #cmakedefine CSV_DIR "@DIR_STRING@"
    

    Then I added this to the main CMakeLists.txt:

    include("${DIR}/include/CMakeLists.txt")
    

    By using doing this, after building it with CMake I can use the variable CSV_DIR anywhere in the program.