multiple definition of inline function

后端 未结 6 1611
情深已故
情深已故 2020-12-08 19:51

I have gone through some posts related to this topic but was not able to sort out my doubt completely. This might be a very naive question.

I have a header file

6条回答
  •  Happy的楠姐
    2020-12-08 20:33

    This answer is divided into the following sections:

    1. How to reproduce the duplicate definition of inline function - func3 problem and why.
    2. Why defintion of func3 is a duplicate instead of func1.
    3. Why it compiles using g++

    How to produce the duplicate definition of inline function - func3 problem

    The problem can be successfully reproduced by

    1. Rename tran.cpp to tran.c
    2. Compile with gcc -o main main.c tran.c

    @K71993 is actually compiling using the old gnu89 inline semantics, which is different from C99. The reason for renaming tran.cpp to tran.c is to tell the gcc driver to treat it as C source instead of C++ source.


    Why definition of func3 is a duplicate instead of func1.

    GNU 89 inline semantics

    The following text is quoted from GCC Document: An Inline Function is As Fast As a Macro explains why func3 is a duplicate definition instead of func1, since func3 (instead of func1) is an externally visible symbol (in GNU89 inline semantics)

    When an inline function is not static, then the compiler must assume that there may be calls from other source files; since a global symbol can be defined only once in any program, the function must not be defined in the other source files, so the calls therein cannot be integrated. Therefore, a non-static inline function is always compiled on its own in the usual fashion.

    If you specify both inline and extern in the function definition, then the definition is used only for inlining. In no case is the function compiled on its own, not even if you refer to its address explicitly. Such an address becomes an external reference, as if you had only declared the function, and had not defined it.

    C99 inline semantics

    If compiled with C99 standard, i.e., gcc -o main main.c tran.c -std=c99, the linker will complain that definition of func1 is a duplicate due to the reason that extern inline in C99 is a external definition as mentioned in other posts and comments.

    Please also refer to this execellent answer about semantic differents between GNU89 inline and C99 inline.

    Why it compiles using g++.

    When compiled with g++, the source program are considered as C++ source. Since func1, func2 and func3 are defined in multiple translation units and their definitions are different, the One Defintion Rule of C++ is violated. Since the compiler is not required to generate dignostic message when definitions spans multiple translation units, the behavior is undefined.

提交回复
热议问题