views:

753

answers:

2

Hi,

I'm trying to learn how to create a C/C++ library in a linux environment but I'm having a problem (probably a trivial one) that online tutorials had not helped to solve.

For definiteness let's say I have a foo.c file with the following code:

//file: foo.c
#include <stdio.h>
void hello(void)
{
  printf("hello!\n");
}

a foo.h:

//file: foo.h
void hello(void);

and a program that uses the function hello() from foo.c, named prog.c:

//file: prog.c

#include "foo.h"

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

The three files are all on the same directory. Then I compiled foo.c with:

gcc -fPIC -c foo.c

and got a foo.o file. Then I used ld to create the library file:

ld -G foo.o -o libfoo.so

But when I try to compile prog.c with:

gcc -o prog prog.c -lfoo

I got an error message:

/usr/bin/ld: cannot find -lfoo
collect2: ld returned 1 exit status

I'm convinced that this is some kind of trivial path problem, but I couldn't find the solution. So my question is really if this procedure above is wrong or if I have to put the libfoo.so file in a special path.

Another question is how this changes if I'm using g++ instead of gcc.

Thanks.

EDIT:

I know I can compile both prog.c and foo.c to prog.o and foo.o an then link them to make an executable. But in my original problem I want to compile foo.c in a way that I can distribute to people who will use my functions in their own programs.

+2  A: 

Try

gcc -o prog prog.c -lfoo -L.

The -L switch adds its argument to the set of paths that ld looks in for library files. The syntax is identical for g++.

Harper Shelby
Hummmm... right. Is there any path in the system where ld looks for the libraries automatically??
Rafael S. Calsaverini
Yes - it's /usr/local/lib/, then /usr/lib/.
Harper Shelby
+2  A: 

ld doesn't search the current directory by default. If you want it to do this you need to use the -L command line option, so if your library is in the current directory you need to add -L. to the last gcc call. If the library is dynamically linked you also need to add the current directory to the environment variable LD_LIBRARY_PATH (I assume you're on linux).

Of course, if your library is in any other non-standard path you need to use that instead of the current directory.

bluebrother