Generate GCC options from #include on Linux

Viewed 96

I'd like to build a tool for students that would recommend which GCC options to use by inspecting the #include they've used. For instance:

#include <math.h>      // recommend -lm
#include <zlib.h>      // recommend -lz
#include <pthread.h>   // recommend -pthread

Is there somewhere a list of such associations for standard and classical libraries? I just need it for GCC and Linux.

-- EDIT

As it looks like that there is no known solution, I've started to build such a list, together with a simple wrapper script inspired from pkg-config: see GitHub repo

1 Answers

You can use the -M option of GCC to list all the header files which will be used for the compilation. After that you should be able to create a script which matches the output with the headers you want to mark.

-- EDIT

Here is a possible script for this ; I don't think it's the most relevant or the best way to do it, but it works pretty well for this usage:

FILES="main.c" # For example

OUTPUT=$(gcc -M $FILES)

for LINE in ${OUTPUT[@]}
do
    case $(echo $LINE | rev | cut -d"/" -f1 | rev) in
        "math.h")
            echo "You should use -lm"
            ;;
        "pthread.h")
            echo "You should use -pthread"
            ;;
        "zlib.h")
            echo "You should use -lz"
            ;;
        # And so on with all the files you want to tag
    esac
done
Related