简体   繁体   中英

How can I make a C++ program to read predefined files after installation on linux

My project folder has the following structure

-Project/
        /src
             -Main.cpp
             -MyReader.cpp
        /headers
             -MyReader.h
        /DataFiles
             -File.dat
             -File1.dat

My class Object.cpp has a couple of methods which reads from File.dat and File1.dat and parse the information to Map objects. My problem is that I am using Autotools (in which I'm very very newbie) for generating config and installer files and I don't know how to make all the DataFiles files accessible for the program after installation. The program doesn't work properly because of the code fails when trying to read those files through relative paths. Locally, the program runs perfectly after executing in terminal make && ./program .

How can I solve this issue? Thanks in advance for your help!

A platform independent way to do this with Autotools is using the $(datadir) variable to locate the system data directory and work relative to that.

So in your Makefile.am file you can create a name like this:

myprog_infodir = $(datadir)/myprog

# Set a macro for your code to use
myprog_CXXFLAGS = -DDATA_LOCATION=\"$(datadir)/myprog\"

# This will install it from the development directories
myprog_info_DATA = $(top_srcdir)/DataFiles/File.dat $(top_srcdir)/DataFiles/File1.dat

# make sure it gets in the installation package
extra_DIST = $(top_srcdir)/DataFiles/File.dat $(top_srcdir)/DataFiles/File1.dat

Then in your program you should be able to refer to the data like this:

std::ifstream ifs(DATA_LOCATION "/File.dat");

Disclaimer: Untested code

I figured out one method and will give my example here:

In my Makefile.am

AM_CPPFLAGS = -D MATRIXDIR="\"$(pkgdatadir)/matrix\""

nobase_dist_pkgdata_DATA = matrix/AAcode.txt  \
matrix/BLOSUM50 matrix/BLOSUM70.50 matrix/BLOSUM100 matrix/BLOSUM50.50 \
matrix/BLOSUM75 matrix/BLOSUM100.50 matrix/BLOSUM55 matrix/BLOSUM75.50 \
... more not shown

I put quite some number of datafiles in the matrix directory, just show a few of them. In my source file, I simply use the macro MATRIXDIR:

scorematrix.cpp:string MatrixScoreMethod::default_path=MATRIXDIR;

This seems to work well for me. You can use other versions of the data automake variable, such as dist_data_DATA instead of pkgdata. It is a good idea to use pkgdata this way your data will not be mixed with other packages. The nobase_ is to tell automake not to strip the matrix directory during install. Those escaped double quotes seems to be needed for string type so that you don't get compiler errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM