Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline qualifier stems from prototype or definition?

Tags:

c++

gcc

clang

I'm not quite sure about this in the standards. Say I have three files like this:

foo.h

#include <iostream>

inline void foo();

void foo()
{
   std::cout << "Foo" << std::endl;
}

foo.cpp:

#include "foo.h"

void baz();

int main()
{
   baz();
   foo();
}

bar.cpp

#include "foo.h"

void baz()
{
   foo();
}

Now, the definition for foo will be compiled into both compilation units foo.o and bar.o. If I understand it correctly, having inlined functions will avoid linker collition. G++ compiled and links this just fine, but with clang++ 2.8 I get this error:

/tmp/cc-7RdmYP.o: In function `foo()':
bar.cpp:(.text+0x50): multiple definition of `foo()'
/tmp/cc-LW3id3.o:foo.cpp:(.text+0x50): first defined here
collect2: ld returned 1 exit status

It seems that clang++ does not see void foo() as an inlined function. It does however, work fine when I add inline to the definition as well.

Do I have to add inline to void foo() as well here to have it be seen as an inlined function, or is this a clang++ bug?

like image 356
Maister Avatar asked Feb 07 '11 18:02

Maister


2 Answers

Odds are that your clang uses C99 inline semantics. In C99, if one of your functions doesn't use "inline" or does include "extern", then the definition is an "external definition", which can only appear once in the program. See inline in C99.

In C++, your program is fine. In Clang SVN, this bug has been fixed and your program should work fine.

like image 123
Johannes Schaub - litb Avatar answered Sep 21 '22 21:09

Johannes Schaub - litb


C++0X draft N3225 says in 7.1.2 Function specifiers:

  • clause 2: A function declaration with an inline specifier declares an inline function
  • clause 4: An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case.

So, to me, it looks like gcc is right & clang wrong, but there's still a (slim) chance that things were (are?) different in C++03..

like image 40
Eugen Constantin Dinca Avatar answered Sep 19 '22 21:09

Eugen Constantin Dinca