Can GCC warn about undefined functions in libraries?

Viewed 372

Consider the following test project:

test.h:

#ifndef TEST_H
#define TEST_H

void test1(int);
void test2(int);

#endif /* TEST_H */

text.c:

#include "test.h"

void test1(int x) { (void) x; }

Oops, I forgot to define test2()! I would like some kind of feedback when I do this, preferably refusal to compile although a warning at least would be nice. However GCC 10.2 (on Ubuntu 20.10) compiles it fine with no warnings:

gcc -Wall -Wextra -Wpedantic -std=c11 -o libtest.o -c test.c

I think I understand why: what if test2() is actually meant to come from another library, maybe a system library? Make it the problem of whichever program ends up linking everything into an executable! But I want to know about it before then. In this case, it's not declared in any included header file. It's not called anywhere. Can that be detected?

I've tried:

  • --no-undefined which resulted in gcc: error: unrecognized command-line option ‘--no-undefined’; did you mean ‘-Wno-undef’?
  • -Wno-undef - accepted but no warning
  • -z,defs - accepted but no warning
  • -Wimplicit-function-declaration - accepted but no warning
  • -Werror=missing-declarations - I know this is for the opposite situation but I was getting desperate.
1 Answers

This isn't possible, as no linking is performed at the stage of assembling a static library.

I'd suggest having a "test container" for your library. Set up your build system to build the test executable any time you are building the library. It could even just be a single .c file in the same directory as the library sources, but obviously not in the list of objects that are part of the library.

The test executable calls all of the functions that you wish to be entry points for the library.

Probably that is something you should be doing anyway in order to test the library's functionality before doing a release.

Related