Pierre-Louis Sauvage
Pierre-Louis Sauvage

Reputation: 113

Getting a string input with make command to use as a main argument in C program

I'm having trouble using makefile commands to get a user input. What I need is to ask the user the name of TXT file (which is located in ./data/), then to use the path to this file as an argument for my main C program.

Make code :

launch-app-conway: app-conway
  @read -p "Enter file name: " FILENAME
  FILEPATH = "./data/"
  FILEPATH += FILENAME
  ./main-program FILEPATH

It outputs "FILEPATH : command not found".

Thanks for the help !

Upvotes: 1

Views: 2255

Answers (2)

blackghost
blackghost

Reputation: 1825

Each line of a recipe spawns a new shell. Therefore, if you set a variable in line 1, then that variable will be forgotten before line line2. You can concatinate the lines using \ As well, you seem to be missing dollar signs (not sure which shell you're using), but typically, a single dollar sign in a recpipe refers to a make variable, and a double is used for shell variables.

What you want is something like:

launch-app-conway: app-conway
    @read -p "Enter file name: " FILENAME; \
    FILEPATH="./data/$$FILENAME"; \
    echo $$FILEPATH

(Note: if you want to cut and paste from here, remember that SI converts tabs to spaces, and Makefiles require spaces).

Upvotes: 1

MadScientist
MadScientist

Reputation: 100946

You have a lot of issues here. First, you're not using variables at all. The value FILENAME is just a text string, a literal word FILENAME. It's not a variable reference.

Second, you seem to be trying to use make variable assignment etc. in your makefile recipe. A makefile recipe (the parts indented by TAB characters) are passed to the shell and you have to use shell syntax (there is no += assignment in the shell for example).

Third, every logical line in a makefile recipe is passed to a different shell, and variable assignments made in a shell are lost when the shell exits, so even if the variable references were correct and you were using correct shell syntax to construct the variable FILEPATH, it would be empty because it was constructed in a different shell.

You can do what you want using this:

launch-app-conway: app-conway
        @read -p "Enter file name: " FILENAME; \
        ./main-program "./data/$$FILENAME"

However, note that if you try to run this makefile with -j it may not work properly since your recipe might not have access to stdin.

Upvotes: 4

Related Questions