Home > Mobile >  Can't compile sample bpf program, bpf/bpf.h is missing
Can't compile sample bpf program, bpf/bpf.h is missing

Time:11-01

I'm trying to compile the sample bpf program in Linux source code. So I downloaded the current kernel source code and entered samples/bpf folder

apt source linux
cd linux-*/samples/bpf

Then I tried to compile a sample program with gcc:

# gcc sock_example.c
sock_example.c:29:10: fatal error: bpf/bpf.h: No such file or directory
   29 | #include <bpf/bpf.h>
      |          ^~~~~~~~~~~
compilation terminated.

And I'm unable to find bpf/bpf.h with apt-file

# apt-file find bpf/bpf.h
(no output)

What was wrong?

CodePudding user response:

You need to install libbpf:

git clone --depth 1 https://github.com/libbpf/libbpf
cd src
sudo make install

CodePudding user response:

The Linux eBPF samples come with a rather long Makefile. It handles a lot of cases and integrates well with the kernel building workflow, but makes it more complicated to build the samples outside of the kernel tree.

For example, this Makefile adds a number of includes directories, such as TPROGS_CFLAGS = -I$(srctree)/tools/lib/, meaning that bpf/bpf.h will not be fetched from your OS' libraries but from tools/lib/ under your kernel repository.

Here are a few options that you can consider to compile your program:

  • Adjust the existing Makefile to use it to build your own programs, for example by adding your kernel code to the tprogs-y target.
  • Install libbpf from the kernel repo (sudo make -C tools/lib/bpf install) or from its GitHub mirror. This should install the headers, and gcc should then be able to find them.
  • Adjust your compile option to tell gcc where to look for the header (gcc -I <path/to/linux>/tools/lib).
  • (Adjust the include path in #include <bpf/bpf.h> to make it point to your library.)
  • Related