Question in creating targets in makefile

Hi,

I have a question related to makefile. I'm new to makefile and I'm in the process of writing a makefile for my RBT build. I have multiple source files and when I compile them I will get multiple object files (one object file for each source file). I'm having problem in creating a target for each object file with out hardcoding the object file names. I read the list of source file names from another make file. Assume the variable SRC_NAMES contains list of source file names (say test1.c test2.c test3.c). Now I want to create target for each objects for it (say test1.obj test2.obj test3.obj). Currently I have written some thing like below,

 
#############################################
OBJS_LIST := $(foreach file,$(SRC_NAMES),$(notdir ${file}))
OBJS_LIST := $(DSP_COMMON_OBJ_LIST:.c=.obj)
 
all: final.exe
 
final.exe: $(OBJS_LIST)
   create exe here
 
$(OBJS_LIST): $(SRC_NAMES)
    compile and generate object file for each source files here.
 
#############################################

This is not working. Since OBJS_LIST contains many object names, compilation action is repeated for many times for the target $(OBJS_LIST). My question is how to split the obj target into multiple targets without hard-coding the target obj names?

Thanks,
Anand

You need a generalized rule for how to get from a "source" file to an "object" file. If your source files carry the extension ".src" and your objects the extension ".obj" this would be:

.src.obj
               <actions here>

Now you only need a special variable which contains only the file name which triggered the rule to use in the action part - and fortunately there is such a thing: "$<". A possible rule would look like:

COMPILE=/path/to/compiler
FLAGS=-a -b -c
.src.obj
               $(COMPILE) $(FLAGS) $<

If the rule is triggered by the file "foo.src" the command executed would be:

/path/to/compiler -a -b -c foo.src

You might want to read the man page of the make-utility to learn more about the various special variables you can use. For instance, there is also a variable for the file name that will be the target of the rule: "$@".

C compilers per default write a file "a.out" instead of naming the object like the source file only with the extension replaced by ".obj". You would have to explicitly tell the compiler which name it should use for its output file with the "-o" option if you do not want this default behavior. This is what "$@" is for:

COMPILE=/path/to/compiler
FLAGS=-a -b -c
.src.obj
               $(COMPILE) $(FLAGS) $< -o $@

I am sure you will be able to adapt this to your needs with careful study of the man page.

I hope this helps.

bakunin

1 Like