0

This is the error I have been getting.

-bash-4.1$ g++ strl.cpp -o -lc-
/tmp/ccRpiglh.o: In function `main':
strl.cpp:(.text+0xf): undefined reference to `plusplus'
collect2: ld returned 1 exit status

Hear is the source code for strl.cpp. This is a simple example that duplicates my problem.

strl.cpp
#include <iostream>
#include <stdlib.h>
#include "libc-.h"

using namespace std;

int main()
{
  cout<<plusplus(5,2)<<'\n';
}

Here is the source for libc.cpp

libc.cpp
#include <iostream>

using namespace std;

int plusplus(int a, int b)
{
  return a + b;
}

Source for libc-.h

libc-.h 
#ifndef _SCANTYPE_H_
#define _SCANTYPE_H_

#include <iostream>
#include <stdlib.h>

#ifdef __cplusplus
extern "C"
{
#endif

  using namespace std;

  int plusplus(int a, int b);

#ifdef __cplusplus
}
#endif 

#endif

I am compiling with the following:

g++ -Wall -shared -fPIC -o libc-.so libc-.cpp
g++ strl.cpp -o -lc-

g++ -Wall -shared -fPIC -o libc-.so libc-.cpp compiles without error.

Why is function plusplus an undefined reference?

Thanks for any insight as to what I am doing wrong.

8bittree
  • 1,769
  • 2
  • 18
  • 25
  • possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Niall Sep 18 '15 at 19:33

3 Answers3

0

What is that 'using' in libc-.h for? Anyway, it looks to me that you need to include this header in libc.cpp too. See https://stackoverflow.com/a/1380926/2406949

Community
  • 1
  • 1
PookyFan
  • 785
  • 1
  • 8
  • 23
0

Don't you need extern C around the function definition? I bet the linker is trying to match the mangled c++ name with the unmangled C name.

And note that you are using C++ features (using), so the check for #ifdef cplusplus is redundant. If it's false your compiles will be failing.

Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53
0

The reference to plusplus() is missing, because it's not provided. You are promising

`int plusplus(int a, int b);`

with C linkage in libc-.h, but are not keeping your promise in libc.cpp. To fix the problem, change the latter file to

// libc.cpp
#include <iostream>
#include "libc-.h"   // include proto-type which has C linkage

int plusplus(int a, int b)
{
  return a + b;
}

Also, you should never do using namespace std; in a header file.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Walter
  • 44,150
  • 20
  • 113
  • 196