1

So, here is the problem.

I have compiled some object files, using gcc -c, and I have cloned them using obj-copy. If the a function of the initial object file was named foo(), then the resulting function names in the cloned objects are: foo1(); foo2(); foo3();

Then, I link those 3 objects, with another file, that contains the main method, and I can invoke each of the function variants by using e.g. foo2();. This work perfectly fine!

However, if I try to create a function pointer to point to those functions by using:

functionPtr=&foo1; \\ tried also w/o the &

then, I get:

error: 'foo2' undeclared (first use in this function)

Any ideas? Does this have to do with the linking?

Paschalis
  • 11,929
  • 9
  • 52
  • 82

1 Answers1

1

foo2 must be declared in a header file somewhere. You've cloned the object files, but the C compiler still needs something to tell it that there's a function called foo2 and what its signature is. If you have a declaration somewhere for the original foo, just make a copy of that and change the name to foo2, and make sure the header is #include'd in your source.

TypeIA
  • 16,916
  • 1
  • 38
  • 52
  • But if I call `foo1();` it works. Why doesn't it work for `fPtr=&foo1;` too? – Paschalis Mar 25 '14 at 18:38
  • 1
    @Paschalis ANSI C [doesn't require a function prototype to call a function](http://stackoverflow.com/questions/2575153/must-declare-function-prototype-in-c); it infers the signature from the way you call it. It won't do that for function pointers, though. – TypeIA Mar 25 '14 at 18:40
  • So, to try understand the reasoning behind this: if I use `foo_99()`(which does not exist anywhere), it will pass the compilation, but will fail on linking. But in function pointers, it needs a reference to the function before the final linking. Is that corrrect? – Paschalis Mar 25 '14 at 18:44
  • Still, using funcions without prototype is frowned upon. It's a legacy from pre-standard c, and most compilers warn you or even treat it as an error if you so desire (you should!). – Deduplicator Mar 25 '14 at 18:50
  • 1
    @Deduplicator I agree. But I was using a prototype `foo()`. And since I was relying to `obj-copy` to rename the reference of `foo()`, I was expecting to rename the prototype too! This is why I got confused! – Paschalis Mar 25 '14 at 18:57