The Quantum Physicist
The Quantum Physicist

Reputation: 26336

Check if a command returns nothing in Makefile

For a C library, I need to check whether the current compiler is for x86_64 due to memory issues. The command I found that exactly meets my requirement:

CXXARCH:=$(${CXX} -dumpmachine | grep -i 'x86_64')

where ${CXX} is either gcc or clang. For an x86_64 machine, this will return a non-empty string. For a 32-bit machine, say Raspberry Pi, this will be empty.

how can I distinguish between the two cases?

I did this:

ifneq (${CXXARCH},)
MAGICVAR:=-DMY_DEFINE
endif

With an $(info) print, I ensured that in a Raspberry Pi, this condition is not being fulfilled, which it should, because the command clang-6.0 -dumpmachine returns: armv7l-unknown-linux-gnueabihf. So why is this condition not being executed? What am I doing wrong?

Upvotes: 6

Views: 2588

Answers (2)

The syntax

$(${CXX} -dumpmachine | grep -i 'x86_64')

is shell syntax. It doesn't do what you want in a Makefile. To expand the CXX variable in Makefile, the preferred syntax is to use $(CXX) (while ${CXX} works too, but $CXX does not). To capture the shell output you need to use $(shell command). Thus

CXXARCH:=$(shell $(CXX) -dumpmachine | grep -i 'x86_64')
ifneq ($(CXXARCH),)
MAGICVAR:=-DMY_DEFINE
endif

Notice that the compiler target has nothing to do with "memory issues" in a resulting program. You can use x86_64-linux-gnu-gcc to compile 32-bit programs (-m32) and get the "same memory issues" that you'd have with a 32-bit compiler.


Finally make sure that you've not confused ifneq and ifeq.

ifneq ($(CXXARCH),)

means "if $(CXXARCH) does not expand to an empty string, then..."

Upvotes: 6

Andrew Henle
Andrew Henle

Reputation: 1

Assuming a POSIX system, pipe the results through wc -l:

CXXARCH:=$(shell $(CXX) -dumpmachine | grep -i 'x86_64' | wc -l)

If the result is zero, there were zero lines with x86_64 in it. That's easier to handle in a makefile than a string value.

(including fixes to get shell syntax)

Upvotes: 1

Related Questions