#ifndef mydll_h_
#define mydll_h_
void hello();
#endif
#include "mydll.h"
int main ()
{
hello ();
return 0;
}
#include <iostream>
void hello()
{
std::cout << "Hello World!\n";
}
#include <iostream>
void hello()
{
std::cout << "Hello World!\n";
}
int main ()
{
hello ();
return 0;
}
g++ -c mydll.cc
g++ -shared -o mydll.dll mydll.o
g++ -o myprog myprog.cc -L./ -lmydll
myprog.cc: In function ‘int main()’:
myprog.cc:4:10: error: ‘hello’ was not declared in this scope
hello ();
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!
>