Daniel Daniel - 1 month ago 6
C Question

C Makefile, Compile parts of the project with different rules

I have a project containing source and header files organized in n folders (let's called them folder1, folder2, ..., foldern)

I want to compile folder1 with -Wall but the rest of them with -w.
The problem is that some folders (2 to n) contains only header files which are included in some of the sources in folder1.

When I compile folder1, -Wall will apply also to the headers in that folder and I do not want that.

This is the makefile I used so far:

CC=gcc
LIBS=-iquotefolder2 ... -iquotefoldern

SOURCES=$(wildcard folder1/*.c) $(wildcard folder2/*.c) ... $(wildcard foldern/*.c)
OBJECTS=$(SOURCES:.c=.o)

folder1/%.o: folder1/%.c
$(CC) -Wall $(LIBS) -c -o $@ $^

folder2/%.o: folder2/%.c
@$(CC) -w $(LIBS) -c -o $@ $^
...

foldern/%.o: foldern/%.c
@$(CC) -w $(LIBS) -c -o $@ $^

lib.dll: $(OBJECTS)
@$(CC) -w -shared -Wl,-soname,$@ -o $@ $^

all: lib.dll


Is there any way to achieve this?
I also tried to compile folder2 to foldern in a lib.a and link that library while compiling folder1 but gcc will (obviously) try to include the headers

Answer

You can't do that with Makefile. Makefile processes only source files, so you can provide flags in Makefile on source file granularity only. In other words, gcc is invoked on source files, and headers are not mentioned in gcc invocations.

However, you can instruct gcc to adjust warnings in different files:

  1. Pass -isystem <dir> flag to gcc - this will make gcc treat headers located dir as system headers. gcc by default does not issue any warnings in system headers.

  2. Use #pragma GCC diagnostic to ignore warnings from source files:

Source:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#include "folder2/bad-header.h"
#pragma GCC diagnostic pop