I am trying to develop an application that uses an external .a static library.
Since this external library file already have the symbols defined in it, is there a way to skip the include statement of header files in the .cpp source files that use it?
In other words - if i already have the .a file, why do i need the .h file?
Thanks in advance
CodePudding user response:
Yes, you have to.
The compiler needs to know the datatypes used by the library and needs to know what parameters functions are taking and what type is the return value. It needs to also to know the global objects used by the library.
In other words - if i already have the .a file, why do i need the .h file?
The compiler does not use object files to retrieve information about functions, data or types. You need to specify it in your source code. Object files are not part of the C language.
You do not need .h
file. You can also type declarations, function prototypes in your source code. .h
file can be included by your source code and be reused in other source code files.
CodePudding user response:
you could do things like this:
#a.cpp
#include <iostream>
void who_are_you()
{
std::cout << "I am A\n";
}
#b.cpp
#include <iostream>
void who_are_you()
{
std::cout << "I am B\n";
}
#main.cpp
#include <iostream>
void who_are_you();
int main()
{
std::cout << "who_are_you()\n";
who_are_you();
return 0;
}
and then
g -c a.cpp
g -c b.cpp
ar -r libA.a a.o
ar -r libB.a b.o
g main.cpp libA.a -o withA
g main.cpp libB.a -o withB
the output of ./withA will be
who_are_you()
I am A
the output of ./withB will be
who_are_you()
I am B
but generally the answer of @0___________ is right, you have to. here if you notice we defined the signature of who_are_you in our main file.
CodePudding user response:
Do i have to include a header file when using an external library?
You technically don't have to. But the header files will make using the library much easier.
why do i need the .h file?
The header file declares and in some cases defines the types, the functions and the variables.
You won't necessarily need to include a header if you can import a module instead.
CodePudding user response:
The compiler needs to know the signature of the resources you use from the library. This can be done by including the appropriate header file, or by providing the signatures yourself.
You do not need to include a header file, as long as you provide signatures/prototypes for the resources you use from the library.
CodePudding user response:
yes always. you can also add your existing functions by using #include
. and the compiler will include the particular file for you.