Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c++ - static library, but I still need headers?

I have a bunch of projects that all could share a "common" static library of classes.

What confuses me is if I make a static library out of these classes and link against it in my projects that I still need the headers of the classes in the static library in my main projects.

What is the benefit of the static library then?

How do companies like Adobe deal with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Static libraries allow you to create a library and use that library in many projects.

The need for header files:

Since the project using the library is programmed and compiled independent of the library, that program needs to know the declaration of the things you're using. Otherwise how would your compiler know you're writing valid code?

A compiler only takes source code as input and produces output. It does not deal with compiled object files or static libraries on input.

The need for linking in the library:

So having the headers allows you to write valid code in your project, but when it comes to link time you'll need to provide the definition which is contained inside the static library.

The linker takes all object files (compiled code) and also all static libraries and produces an executable or binary.

More info about static libraries (benefits, comparing dynamic, etc...):

Amongst other things, it is nice to separate your project into libraries so that you don't end up with 1 huge monolithic project.

You do not need to distribute the source code (typically in the .cpp files) this way.

If you were to simply include all the .cpp files in every project that used the common library then you would have to compile the .cpp files each time.

An advantage of static libraries over dynamic libraries is that you can always be sure that your programs will be self contained and that they are using the correct version of the library (since they are compiled into the executable itself). You will also have a slight speed advantage over dynamic linking.

Disadvantages of static libraries over dynamic libraries include that your file sizes will be bigger because each executable needs their own copy, and that you can't swap out a different version of the library since it's not dynamically loaded.

Re your question: How do companies deal with this:

A typical company will make use of both static and dynamic libraries extensively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...