6

I just cant see what Im doing wrong here:

Q. Why is my library not being found by g++ when compiling the program with a shared object?

Im trying to include a shared library to my c++ program:

g++ -fpic -c sha.cpp
g++ -shared -o libsha.so sha.o
g++ main.cpp -o main -L. -lsha

where sha.cpp and sha.h are the library files and main.cpp is my program.

Ive tried the same with static library which works find:

g++ -static -c sha.cpp -o libsha.o
ar rcs libsha.a libsha.o
g++ main.cpp -o main -L. -lsha

The platform is cygwin on windows and here is the output:

rob@pc /cygdrive/c/src/a
$ g++ main.cpp -o shatest -L. -lsha
/usr/lib/gcc/i686-pc-cygwin/4.3.4/../../../../i686-pc-cygwin/bin/ld: cannot find -lsha
collect2: ld returned 1 exit status

Ive read all forum posts but the library is in the same folder!

$ ls
libsha.so  main.cpp  sha.cpp  sha.h  sha.o

The reason im doing this is that on another platform, a library is being created whereby when one object is called, it works, but the app crashes when the second object is being constructed. Im doing the above as a simple test! (annoyingly not so simple).

source files below:

main.cpp

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "sha.h"

void *thread_one( void *ptr );
void *thread_two( void *ptr );

main()
{
     pthread_t thread1, thread2;
     int  iret1, iret2;

     /* Create independent threads each of which will execute function */
     iret1 = pthread_create( &thread1, NULL, thread_one, 0);
     iret2 = pthread_create( &thread2, NULL, thread_two, 0);

     /* Wait till threads are complete before main continues. Unless we  */
     /* wait we run the risk of executing an exit which will terminate   */
     /* the process and all threads before the threads have completed.   */
     pthread_join( thread1, NULL);
     pthread_join( thread2, NULL); 

     printf("Thread 1 returns: %d\n",iret1);
     printf("Thread 2 returns: %d\n",iret2);
     exit(0);
}

void *thread_one( void *ptr )
{
    printf("Run thread_one\n");
    CObj1 obj;
}

void *thread_two( void *ptr )
{
    printf("Run thread_two\n");
    CObj2 obj;
}

sha.cpp

#include <stdio.h>
#include <stdlib.h>

#include "sha.h"

CObj1::CObj1()
{
    printf("CObj1\n");
    a = 10;
    printf("CObj1: %d \n", a);
}

CObj2::CObj2()
{
    printf("CObj2\n");
    a = 10;
    printf("CObj2: %d \n", a);
}

sha.h

#ifndef LIB
#define LIB

class CObj1
{
public:
    CObj1();

private:
    int a;
};

class CObj2
{
public:
    CObj2();

private:
    int a;
};

#endif
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
user1453495
  • 61
  • 1
  • 2

0 Answers0