eduherminio
eduherminio

Reputation: 1694

Sharing a variable in a cmake file and a shell script (or passing it from one to another)

I'm starting to work with OpenCV and I'm setting everything up.

Since I compile the files with cmake, I've just learnt to use the following file (CMakeLists.txt):

set(namefile "0_Intro")

cmake_minimum_required(VERSION 2.8)
project( namefile )
find_package( OpenCV REQUIRED )
add_executable( ${namefile} ${namefile}.cpp )
target_link_libraries( ${namefile} ${OpenCV_LIBS} )

I've also learned to use a simple shell script (compile.sh) to build everything faster.

#!/bin/bash
set -e
cmake .  #&> /dev/null
make
./0_Intro

My question is:

How can I share the variable namefile in both of my files so that not having to change both of them when I compile something different?

Is it possible to read it from both CMakeLists.txt & compile.sh (together with some other variables to use as arguments in the execution, in compile.sh)?

Alternatively, how could I pass it from the CMakeLists.txt to my .sh? (I'd rather not have to do this, reading the variable from a third file seems much more comfortable).

Thanks in advance,

Eduardo

Upvotes: 0

Views: 4011

Answers (3)

eduherminio
eduherminio

Reputation: 1694

In case it's useful for anyone else:

galsh83's answer modified so that file names are read from a .txt file (which avoids having to change the shellscript to compile a different file / open a different picture).


compile.sh:

#!/bin/bash
set -e
source filedata.txt
export env_filename=$filename
cmake .  &> /dev/null
make
./$filename $imagename

CMakeLists.txt:

set(filename $ENV{env_filename})

cmake_minimum_required(VERSION 2.8)
project( filename )
find_package( OpenCV REQUIRED )
add_executable( ${filename} ${filename}.cpp )
target_link_libraries( ${filename} ${OpenCV_LIBS} ))

filedata.txt:

filename="DisplayImage"
imagename="Pictures/example.png"

Upvotes: 0

galsh83
galsh83

Reputation: 570

You could export environment variables and access them both in bash and in cmake. For example, I could write this bash script:

#!/bin/bash
set -e
export namefile=0_Intro
cmake .  #&> /dev/null
make
./$namefile

And this CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

set(namefile $ENV{namefile})

project(${namefile})

find_package( OpenCV REQUIRED )
add_executable( ${namefile} ${namefile}.cpp )
target_link_libraries( ${namefile} ${OpenCV_LIBS} )

Upvotes: 4

Vetinari
Vetinari

Reputation: 1

Try:

cmake_minimum_required(VERSION 2.8)
project( ${namefile} )
find_package( OpenCV REQUIRED )
add_executable( ${namefile} ${namefile}.cpp )
target_link_libraries( ${namefile} ${OpenCV_LIBS} )

and call 'cmake -Dnamefile:STRING= your filename'

Upvotes: 0

Related Questions