Enable error when linking if a function is not implemented

与世无争的帅哥 提交于 2021-02-10 08:44:38

问题


I noticed that when linking a project using G++, if there are functions that are declared, but not implemented, there are no errors, unless I try to call them.

Q1: Is it possible to enable an error (or at least warning) if a function is declared but not implemented?

Q2: Why this behavior?

(Note: I am using G++ 4.7.0, ld 2.22 if that is the linker used by gcc, from the mingw package)


回答1:


A2: An entity such as a non-inline function with external linkage can have zero or one definitions in a program. It is only required to have one definition if it is actually used (strictly odr-used) - e.g. by being called. g++ would be in error if it issued an error for an undefined function that wasn't used.

A1: So it is not possible (in a conforming way) to force this to be an error.




回答2:


Write unit tests. If a function isn't there, the code that tests it will fail.




回答3:


There is no way to get an error in a single compilation unit (at compilation time) if a function is only declared. Because that function could be defined in a different compilation unit.

You could (assuming a Linux system with plugins enabled in the compiler) write a GCC plugin, or better, a MELT extension (MELT is a high-level domain specific language to extend GCC), which for instance would make an array of pointers to every declared function (so, if the function is not defined, you'll get an error at link time). You could also make a MELT extension which warns for every undefined, but declared, function.

Also, there are sometimes good reasons to declare but not define a function, e.g. when it should be provided by a plugin, or another object or library.

Also, header files usually declare functions but don't define them. These functions are usually provided, at link time, by libraries.




回答4:


You can make the linker generate errors for unreferenced, undefined member functions by making them virtual. Obviously this has other implications so I would recommend using the preprocessor for this. Something like:

#ifdef TEST_COMPLETE_INTERFACE
#define REQUIRE_DEF virtual
#else
#define REQUIRE_DEF
#endif


class myClass
{
public:
    REQUIRE_DEF void someMethod();
};

You can periodically check that everything builds with TEST_COMPLETE_INTERFACE defined. This won't work for static methods or free functions.




回答5:


There's a GCC specific attribute:

void f() __attribute__((error("not implemented")));

int main() {
    f();
}

Gives

error: call to 'f' declared with attribute error: not implemented

This attribute can also be used on class methods. Supported since at least GCC 4.4.



来源:https://stackoverflow.com/questions/12286223/enable-error-when-linking-if-a-function-is-not-implemented

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!