Monday, March 28, 2022

[SOLVED] Using a static library in c (.a file)

Issue

I am trying to create a static library using a shell script.

For creating the library I used following script:

gcc -c -Wall -Wextra -Werror *.c
ar -cr libft.a *.o

There are 5 different functions in 5 .c files.

Now I wanted to test the library and created a main.c file with this content:

#include "libft.a"

int     main(void)
{
    ft_putstr("hello");
}

Compiling the main.c (with gcc main.c) returns 419 warning and at least 20 errors looking something like this:

./libft.a:4:492: warning: null character ignored [-Wnull-character]
  ...<U+0000>UH<89><E5>H<83><EC><U+0010>@<88>}<FF><BF><U+0001><U+0000><U+0000><U+0000>H<8D>u...

Before this I was working with .h files which worked fine but this time I wasn't supposed to create a .h file so I don't what to do know.


Solution

#include "file_name" means like "please copy and paste the contents of the file file_name here", so it shouldn't be used with .a file.

You can write the declaration of the function to use directly instead of using .h file.

/* guessed from usage, please use correct argument and return type */
void ft_putstr(const char*);

int     main(void)
{
    ft_putstr("hello");
}

Then compile the source code with linking with the library:

gcc main.c -lft


Answered By - MikeCAT
Answer Checked By - Marilyn (WPSolving Volunteer)