Dobob Dobob - 3 months ago 25
C++ Question

Cygwin linking shared library




UPDATE:

Removed old question about .so files. They aren't intended to work on Windows.

I solved the below using a header file. I am guessing it is a standard convention to use .h file every time you link using C++?

mydll.h:

#ifndef mydll_h_
#define mydll_h_
void hello();
#endif


myprog.cc:

#include "mydll.h"
int main ()
{
hello ();
return 0;
}


mydll.cc:

#include <iostream>

void hello()
{
std::cout << "Hello World!\n";
}





Alternatively, I tried .dll library using Cygwin with this guide: https://cygwin.com/cygwin-ug-net/dll.html

The compilation for their .c files work, but I am trying to get it to work for my .cc files. Any ideas?

mydll.cc:

#include <iostream>

void hello()
{
std::cout << "Hello World!\n";
}


myprog.cc:

int main ()
{
hello ();
return 0;
}


I typed:

g++ -c mydll.cc
g++ -shared -o mydll.dll mydll.o


But when I type:

g++ -o myprog myprog.cc -L./ -lmydll


I get:

myprog.cc: In function ‘int main()’:
myprog.cc:4:10: error: ‘hello’ was not declared in this scope
hello ();

Answer

You're facing a compiler problem; not a linker problem. The compiler is telling you that when it compiles myprog.cc, it can't find function hello().

You need to write a function declaration for hello(). Note: you're function definition for hello() is in mydll.cc.

A function declaration would simply be:

void hello();

(1) You could place this one line of code in your myprog.cc above int main().

(2) You could also place this one line of code in a header file that is included at least by myprog.cc and optionally by mydll.cc. But good programming practice dictates that the header file should be included by both.

If you follow option 1, the following version of myprog.cc will fix your compiler error:

void hello(); // "extern void hello();" would be more proper.

int main ()
{
  hello ();
  return 0;
}  

Option 2 would entail:

myprog.cc:

#include <mydll.h>

int main ()
{
  hello ();
  return 0;
}  

Either way results in successful compilation and execution:

>g++ -c mydll.cc
>g++ -shared -o mydll.dll mydll.o 
>g++ -o myprog myprog.cc -L./ -lmydll
>./myprog.exe
Hello World!
>
Comments