Reputation: 1704
I'm new to C and stuck on this. The answer here seems widely accepted, but I believe I'm following the correct format and still getting issues.
Here's the offending line in main() (in main.c)
PrintWrapper(PrintFunction, *decoded); // *decoded is a char
The PrintFunction (also in main.c):
void PrintFunction(char c)
{
printf("%c", c);
}
And the prototype declaration (in p1a2.h - in the same directory as main.c)
extern void PrintWrapper(void (*)(char), char c);
The actual source is hidden away in printwrapper.o (same directory as main.c). This is for an assignment and is a very contrived usage of passing a function as a parameter. I compile the program with
g++ main.c printwrapper.o -Wall -g -o tnine
and get the compiler error (the backtick is not a typo if that is relevant)
<path>/main.c:42: undefined reference to `PrintWrapper(void (*)(char), char'
Why does this happen? I'm hoping it's me overlooking something simple.
Upvotes: 2
Views: 160
Reputation: 37954
You should use gcc
instead of g++
to compile C code. The latter front-end is for C++ code, which symbols are subject to name mangling. Assuming that you are really asking about C language, the proper way to compile your project is:
gcc main.c printwrapper.o -Wall -g -o tnine
Here is some working sample:
#include <stdio.h>
#include "pla2.h"
void PrintFunction(char c)
{
printf("%c\n", c);
}
int main(void)
{
char c = 'a';
char *decoded = &c;
PrintWrapper(PrintFunction, *decoded);
return 0;
}
extern void PrintWrapper(void (*)(char), char c);
extern void PrintWrapper(void (*f)(char), char c)
{
f(c);
}
then:
$ gcc -c printwrapper.c
$ gcc main.c printwrapper.o -Wall -g -o tnine
$ ./tnine
a
Upvotes: 1
Reputation: 186
As you are using g++, the compiler expects the function name to be mangled (for more information see this wikipedia article.
To fix the issue, use gcc
instead of g++
or try the following:
extern "C" void PrintWrapper(void (*)(char), char*);
Upvotes: 4
Reputation: 96941
The code you showed us is valid.
Looks like printwrapper.o
just don't contain such function.
Upvotes: 1