0

I am trying to execute basic code in C and C++ in Linux environment. I am using eclipse to run it. Current project is created as C project.

All I am trying to do is to call a function from different file in same folder. I have my main in sample.c, In main I would like to call function sum(int a, int b) in A.c. I was able to run it. But when I rewrite same function sum in A.cpp(a C++ template file) it throws linker error.

gcc  -o "Test"  ./sample.o 

./sample.o: In function main':/home/idtech/workspace/Test/Debug/../sample.c:19: undefined reference to sum' collect2: ld returned 1 exit status make: * [Test] Error 1

I need help in calling functions in C++ file from C file in same folder. Please help me to solve this linker issue.

Thanks

Harsha

0decimal0
  • 3,884
  • 2
  • 24
  • 39
Harsha
  • 17
  • 1
  • 5
  • In general it's best to post code snippets to help others diagnose your problem. However I can guess that you need to use `extern "C"`. Try here: http://stackoverflow.com/questions/1041866/in-c-source-what-is-the-effect-of-extern-c/1041880#1041880 – JoshG79 Jul 12 '13 at 17:08

1 Answers1

2

The C++ compiler mangles symbol names in order to encode type information. Typically, when writing C++ functions that should be exposed to C code, you'll want to wrap the function in an extern "C" { ... } block, like so (or just prefix it with extern "C" as @DaoWen pointed out):

A.cpp:

extern "C" {
    int sum(int a, int b)
    {
        return a+b;
    }
}

caller.c:

extern int sum(int a, int b);
...
int main() { sum(42, 4711); }

By marking a function as extern "C", you're sacrificing the ability to overload it, because different overloads are distinguishable only by their mangled symbol names, and you just requested that mangling be turned off! What it means is that you cannot do this:

extern "C" {
    int sum(int a, int b) { return a+b; }
    float sum(float a, float b) { return a+b; } // conflict!
}
Martin Törnwall
  • 9,299
  • 2
  • 28
  • 35
  • 2
    If you only have one such function you can just put the `extern "C"` inline with the function signature instead of introducing a new block: `extern "C" int sum(int a, int b) {` – DaoWen Jul 12 '13 at 17:09
  • Upvoted for not only explaining why it doesn't work (mangling), but also the **disadvantage** of the solution (no overloading). – Aaron Burke Jul 12 '13 at 17:38