building Linux kernel on Mac OS X

Alfred Zhong picture Alfred Zhong · Apr 4, 2012 · Viewed 36.3k times · Source

I am doing a project to modify the Linux kernel. I have a desktop Linux machine and I have no problem building kernel on it.

However, I am going on a trip and I want to work on my way. I only have a MacBook. When I tried to build the Linux kernel, it complained that elf.h was not found.

I download an elf.h from internet. Now it complains: NO ELF

I tried copying the entire /usr/include from my Linux desktop, and set it as the include directory, and still get strange errors like "u8" not declared

What is the standard way of doing kernel development on Mac? I have a virtual machine running Linux on the same Mac, and it will be used to test the modified kernel. However, I don't really want to build kernel on it, as it is kinda slow.

Answer

mpontillo picture mpontillo · Apr 5, 2012

First, I agree that it's usually simpler to just use a Linux VM. That said, if you really want to do this, I have successfully compiled Linux kernel code using the procedure below.

Before you can even start, you may need to install the Linux source tree on a case-sensitive filesystem on your Mac. (the default HFS filesystem is case insensitive.) I won't cover that here, but a lot of people do this to compile the Android source tree, so you can use Google to find instructions.

First you'll need the following files to cross-compile a kernel on an OS X box (copy them from your known-working Linux VM to your local /usr/include):

/usr/include/elf.h
/usr/include/features.h
/usr/include/bits/predefs.h
/usr/include/bits/wordsize.h
/usr/include/gnu/stubs.h
/usr/include/gnu/stubs-64.h

Next you'll need malloc.h to be in the expected location for a Linux system, so do:

sudo ln -s /usr/include/malloc/malloc.h /usr/include/malloc.h

Finally, you'll need to worry about whether or not the compiler installed on your system is suitable for building the Linux kernel. I have used this procedure for kernels compiled for Android, using an appropriate cross-compiler toolchain, but I'm not sure if you can successfully compile a Linux kernel with the default gcc compiler on OS X (assuming you have the one that comes with Xcode...)


EDIT: You may also want to follow the steps pointed out in the bug linked in the comment above from "nmagerko", to ensure you have the correct dependencies, and the GNU version of sed. In particular:

$ sudo port install libelf
$ sudo port install gsed