1

Let me explain the context first. I have a header with a function declaration, a .c program with the body of the function, and the main program.

foo.h

#ifndef _FOO_H_ #define _FOO_H_ void foo(); #endif 

foo.c

 #include<stdio.h> #include "include/foo.h" void foo() { printf("Hello\n"); } 

mainer.c

#include <stdio.h> #include "include/foo.h" int main() { foo(); return 0; } 

For the purpose of this program, both the header and the static library need to be in separate folders, so the header is on /include/foo.h and the static library generated will be on /lib/libfoo.a, and both .c programs on the main directory. The idea is to generate the object program, then the static library, then linking the static library to create the executable, and finally executing the program.

I have no problem in both creating the object program and the static library.

$ gcc -c foo.c -o foo.o $ ar rcs lib/libfoo.a foo.o 

But when I try to link the static library...

$ gcc -static mainer.c -L. -lfoo -o mainfoo 

It gaves to me an error, claiming the static library can't be found

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

It's strange, considering I asked before how to work with static libraries and headers on separate folders and in this case the static libraries were found. Any idea what I'm doing wrong?

1
  • 1
    It's in lib not . Commented Apr 9, 2013 at 22:46

3 Answers 3

2

Change -L. to -Llib as it looks like you create the .a file there.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not an expert in compiling programs with subdirectories associated, but is there any advantage using -Llib compared with -L./lib? (I don't want to be misunderstanded, both answers solve the problem, but anyway I want to know).
-Llib is cleaner as the "./" in my answer is just redundant information.
1

Basically the linker is telling you that it cannot find the library foo. It normally searches in the default library directories + any you give it with the -L option. You're telling it to look in the current directory, but not in lib where libfoo.a is located, which is why it can't find it. You need to change -L. to -Llib.

Comments

1

I am not completely sure that I understand your directory structure, but maybe what you need is this:

gcc -static mainer.c -L./lib -lfoo -o mainfoo 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.