Conditional Compilation

Last week I had the (dis)pleasure of porting some code to Mac, and today it came time to merge with the original codebase. As helpful as it was to use macros for different code paths, we needed something in the makefile to optionally add flags when compiling on Mac.

// This is all well and good
#ifndef __APPLE__
// Do your Linux-y includes here
#else
// Do your Apple-y includes here
#endif

Apparently, there are a couple conventions for doing this. First, you can inject a configuration step (à la autoconf, for example) which would detect what platform you’re building on in a robust way and build a Makefile for you. Second, if you’re lazy or autoconf would be like hitting a fly with a hammer, you can use make’s conditionals:

# Ensure that this gets declared in time,
# and fill it with the result of `uname`
UNAME := $(shell uname)

# If the environment is Darwin...
ifeq ($(UNAME), Darwin)
CXXFLAGS = # Something Apple-y
else
CXXFLAGS = # Something Linux-y
endif

Simple enough!

Tagged with:
 

Make With Multiple Cores

I was building something, and I remembered a friend was saying a while ago that you could tell gcc how many cores to use when building something. I don’t know if that’s true or not, but it turns out you can certainly tell make:

make -j(number of cores to use)

For example,

make -j2

I took a screen capture of System Monitor after building each way (make and make -j2), to see the difference. The first box is using just one core, and the second is using both.

Multicore Make

I had initially thought I’d have to tell gcc, and so I had planned to edit the makefile to automatically find the number of cores on the system, and then run gcc with that as an argument, so I went in search of how to find the number of cores on a Linux system. It turns out the easiest way to get that number that I came across was to use /proc/cpuinfo:

cat /proc/cpuinfo | grep 'cpu cores' | head -1 | sed -r 's/^.+([[:digit:]]+)/1/'

Tagged with: