Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does typedef struct produce a link failure

So I have a piece of code that looks like this.

typedef struct {
  int foo;
  int bar;
  void foobar(int, char*);
} mystruct;

and

void mystruct::foobar(int x, char* y) { return; }

and

mystruct obj;
obj.foobar(17, "X");

This all compiles, links and runs perfectly. Except when it doesn't. On one compiler it works, and on another compiler (Android GCC) it fails with a link error: unsatisfied reference.

If I change it like this, it compiles and links.

struct mystruct {
  int foo;
  int bar;
  void foobar(int, char*);
};

I think I kind of know why, but I can't explain it properly and I can't find it in the standard. Can anyone explain it to me and find the proper reference?

Edit: I thought it was pretty obvious to all concerned that this is C++ code. I tagged it; function in a struct is not valid C; but just to be clear the file has a CPP extension and the compiler treats it as C++.

Edit: an answerer noticed that the call is a literal and therefore const, but the arg is non-const. This is not a critical factor because (a) the compiler passed it (b) the linked failed regardless of argument types.

Edit: My theory was that this is related to anonymous struct types passed to the linker so that declaration and call compiled separately did not match. It seems this may not be correct, in which case it may just be a subtle compiler bug.

Edit: out of curiosity, can anyone reproduce this behaviour? The actual compiler is Android NDK, recent download, and whatever version of GCC comes with that. If other compilers do/do not have this problem, that could be the answer.

like image 392
david.pfx Avatar asked Feb 04 '14 10:02

david.pfx


1 Answers

I'm thinking it's a compiler bug. The following more extreme example is still OK:

typedef struct { void f(); } f;
void f::f() { }

From GCC buglist. I.e. you're allowed to use a typedef name to define a member function, even when that member function has the same name as the typedef.

like image 171
MSalters Avatar answered Oct 26 '22 08:10

MSalters