Start New Discussion within our Linux and Unix Community

I want to replace a directory path(/home/cmac) insine root/c4/build/makeit where makeit it a file written in vim editor and in that script I have mentioned the path which needs to be replaced, with a variable name. I want to make the script in the root so that anywhere this /home/cmac/ is used gets replaced with the variable since /home/cmac/ is common in each path. Can you please help me out?

In your makefile, you can declare a variable like this:

MYFILEPATH = /home/cmac/

Then for the build targets in your makefile, you can use the variable like this:

targetname: $(MYFILEPATH)filename.cpp
    g++ -Wall -O2 -c $(MYFILEPATH)filename.cpp

Although personally; rather than using an absolute path (like /home/cmac/), I'd use a relative path (e.g. ../cmac/). Obviously your path would depend on the location of your makefile, relative to your source files.

As a quick practical example:
Say I have a main project directory (called myProject) containing two other directories (src and build).
The src directory contains several c++ files:
foo.h, foo.cpp, bar.h, bar.cpp and main.cpp
The build directory will contain the makefile and is where I want the .o files and the final binary to be placed.

So, the makefile is in /home/jason/projects/myProject/build/ and all of the source files are all in /home/jason/projects/myProject/src/
Instead of using the really long absolute paths above, I can use a relative path instead. So to get to the source files from the build directory, the relative path is ../src/. So I can use the relative path (../src/) in my makefile instead!

So my makefile looks like this:

MYFILEPATH = ../src/
CC = g++
CFLAGS = -Wall -O2
OBJECTS = main.o foo.o bar.o

all: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o main

main.o: $(MYFILEPATH)main.cpp
    $(CC) $(CFLAGS) -c $(MYFILEPATH)main.cpp

foo.o: $(MYFILEPATH)foo.cpp
    $(CC) $(CFLAGS) -c $(MYFILEPATH)foo.cpp

bar.o: $(MYFILEPATH)bar.cpp
    $(CC) $(CFLAGS) -c $(MYFILEPATH)bar.cpp

    rm ./main ./*.o

That's a pretty extreme example there. Several repetetive bits of code have been put into variables in the above makefile. MYFILEPATH is the variable storing the path to the source files. CC holds the name of the compiler (g++), CFLAGS stores the compiler flags we want to use when compiling, OBJECTS is the list of objects we depend upon in order to build the main executable.

So to declare a variable, you just give it a name and assign it a value. I usually name my variables in all upper-case characters, so I can easily identify them in my build scripts.

NAME = value
MYPATH = ../src/

and then to use the variable elsewhere in the makefile you enclose the variable name with $()

Hope this is of some help to you!

This article has been dead for over six months. Start a new discussion instead.