C++ compiles and links with pointer to undefined function

Viewed 580

This code:

void undefined_fcn();
void defined_fcn() {}

struct api_t {
    void (*first)();
    void (*second)();
};
api_t api = {undefined_fcn, defined_fcn};

defines a global variable api with a pointer to a non-existent function. However, it compiles, and to my surprise, links with absolutely no complaints from GCC, even with all those -Wall -Wextra -Werror -pedantic flags.

This code is part of a shared library. Only when I load the library, at run-time, it finally fails. How do I check, at library link-time, that I did't forget to define any function?


Update: this question mentions the same problem, and the answer is the same: -Wl,--no-undefined. (by the way, I guess this could even be marked as duplicate). However, according to the accepted answer below, you should be careful when using -Wl,--no-undefined.

2 Answers
Related