1

I have a makefile:

SOURCES= helloworld.c   

ifeq ($(OSNAME), linux)
    # Object files needed to create library
    OBJECTS=$(SOURCES:%.c=%.o)
endif

# Windows Microsoft C/C++ Optimizing Compiler Version 12
ifeq ($(OSNAME), win32)
    OBJECTS=$(SOURCES:%.c=%.obj)
endif

#OBJECTS=$(SOURCES:%.c=%.o)  #without this line print won't output anything
print:
    @echo $(OBJECTS)

When I call make print (on linux and macOS), it prints empty line unless I uncomment the #OBJECTS=$(SOURCES:%.c=%.o) line.

Why is this happening? Arn't all variables global?

user2577547
  • 93
  • 1
  • 10

2 Answers2

2

Hint 1): You can print out every variable from make with the following command:

SOURCES= helloworld.c

$(info sources: $(SOURCES))
$(info osname: $(OSNAME))
$(info os: $(OS))

Hint 2)

As you can see from the output in linux it returns:

sources: helloworld.c   
osname: 
os: 

you can see that OSNAME is not set on linux at all, so your check ifeq ($(OSNAME), linux) will always fail!

To get the OS information, checkout this link:

OS detecting makefile

Klaus
  • 24,205
  • 7
  • 58
  • 113
  • Just a small suggestion -- change to `$(info SOURCES: _$(SOURCES)_)`. This reveals whitespace at the beginning or end of a variable which can often be the case of hard to find makefile errors. – HardcoreHenry Mar 11 '18 at 13:59
0

I gave a test to your Makefile but to no avail. While it is possible that it should work in general, it does not seem to resemble other examples for testing OS. Hence I'm tempted to suggest that your conditionals, at least for Linux where I tested, do not evalute to true, hence the variable is not set.

Here is a rewritten example that seems to work on Linux:

SOURCES= helloworld.c   

UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
    # Object files needed to create library
    OBJECTS=$(SOURCES:%.c=%.o)
endif

# Windows Microsoft C/C++ Optimizing Compiler Version 12
ifeq ($(OS),Windows_NT)
    OBJECTS=$(SOURCES:%.c=%.obj)
endif

print:
    @echo $(OBJECTS)

Output (for me on Linux):

db@vm1:~/projects/here> make
helloworld.o

This example was mostly inspired by the following gist:

https://gist.github.com/sighingnow/deee806603ec9274fd47

dbalakirev
  • 1,918
  • 3
  • 20
  • 31