1

I want to compile these files into executable.

//main.c
#include <stdio.h>
#include <mylib.h>

int main(void){
  call_hello_world();
  return 0;
}
//mylib.h
void call_hello_world(void);
//mylib.c
#include <mylib.h>
#include <stdio.h>

void call_hello_world( void ) {
  printf( ”Hello world!” );
}

I tried

gcc -c -I. -fPIC -o mylib.o mylib.c 
gcc -shared -o libmylib.so mylib.o
gcc -c -o main.o main.c
gcc -o hello main.o -L. -lmylib

but at the third step, I got stucked because it couldn't find my 'mylib.h'. My professor said I needed to change 'LD_LIBRARY_PATH' so I tried to add this export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/dev/shm my .zshrc but it still didn't work for me. Any suggestions what I should do?

haruhi
  • 177
  • 1
  • 13
  • 1
    If you build a static archive, then you can `gcc -o hello main.o -L. -l:libmylib.a`. You won't have to dick around Linux path problems. Another possibility is `gcc -o hello main.o -L. -lmylib -Wl,--enable-new-dtags -Wl,-R,'$ORIGIN/.'`. It will also avoid the Linux path problems, but you need to keep the library in the same directory as the executable. In both cases, you won't need to waste time with `LD_LIBRARY_PATH`. – jww Dec 27 '19 at 13:22

2 Answers2

1

These are the commands needed :

gcc -c -I. -fPIC -o mylib.o mylib.c
gcc -shared -o libmylib.so mylib.o
gcc -c -I. -o main.o main.c
gcc -o hello main.o libmylib.so

Then in your shell:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/full/path/of/directory/containing/libmylib-so

Philippe
  • 20,025
  • 2
  • 23
  • 32
1

There are several issues with your approach.

First, there is a difference between including a header file like this #include <mylib.h> and including it like that #include "mylib.h".

The first option is usually used to include standard library header files, that should be located in the standard set of directories according to the FHS on Linux.

The latter is the option you might want to use as it is usually used to include user-defined headers and tells the preprocessor to search in the directory of the file containing the directive. (See @quest49 answer's https://stackoverflow.com/a/21594/3852949)

The LD_LIBRARY_PATH environment variable is used to indicate where libraries should be searched for first before looking into the standard set of directories.

So what you would want to do to make your main.c file compile, and after changing #include <mylib.h> directive to #include "mylib.h", is to either :

  • Add the include file into the directory where your main.c file is located
  • Indicate where the include file path is with -I option to gcc
Storm
  • 717
  • 6
  • 11