c++ - Linking to a project cannot find header file -
i want make simple static library, , link project. there 3 source files (all in same directory) create library: main1.cpp
, header1.h
, , header2.h
. main1.cpp
contains line #include "header1.h"
, , in turn header1.h
contains line #include "header2.h"
. create library, use add_library(foo static main1.cpp)
in cmakelists.txt
file. running cmake
, make
creates file libfoo.a
expected.
i have project, file main2.cpp
, contains line #include "header1.h"
. in cmakelists.txt
file project, use add_executable(bar main2.cpp)
, target_link_libraries(bar foo.a)
create executable linked static library. copy foo.a
, header1.h
files , place them in same directory project.
the problem is, during compilation of second project, following error:
header1.h: fatal error: header2.h: no such file or directory
so telling me header2.h
cannot found, though referenced in header1.h
. however, have thought contents of foo.a
contain of content of header2.h
when library built? surely not supposed include all of header files first project when want build second project?
thanks :)
short answer: need header files expose functionality wish library export. in other words, if header file contains functions used within library not need expose header files unless header file expose includes header file.
there seems disconnect between library contains , header file does. simplicity lets limit purpose of header files having function prototypes (this simplification removed later). purpose of header file tell new code (that not part of library) function looks like, in name, parameters , return type. when compiling new application if not have information not know how handle things such how pass arguments , how handle return value. note did not include header file says function does, in machine code function. library contains. need both parts in order compile application.
this can extended other things find in header files, such structs. key idea application still needs information such function prototypes , struct definitions.
also need remember #include
does. in simplest form grabs contents of specified file. if 1 header file includes another, contents of second grabbed.
note applies whether static or shared library.
this next part might not trying information future visitors , might find useful:
now lets header1.h
contained functions wish expose while header2.h
contained functions wish internal. instead of having header1.h
include header2.h
should include them separately in source files, wrap them in header file can include, or have header2.h
include header1.h
if dependencies allow that. way need ship header1.h
library users. not cannot use functions in header2.h
still exposed library, header files not control that, make more difficult use them. if want prevent library user using function not intend expose check out so question.
Comments
Post a Comment