0

I am new to CMake. Can somebody tell me why there is an error when changing the order of item in target link libraries.

target_link_libraries(HTTPCPP 
                        config
                        http
                        core
                        utils
                        )

above CMakeList.txt show error :

undefined reference to VAR

VAR is defined in config library. and included in http,core,utils library.

in the other hand, if i move config to the last of target_link_libraries the code worked fine.

target_link_libraries(HTTPCPP 
                        http
                        core
                        utils
                        config
                        )
  • Depending on your linker, dependency is a "pay it forward" kinda thing. Ex: you have `VAR` in `config`, Linkers tend to be a use-it-or-lose-it mentality Nothing prior to `config` has stated a need for `VAR`, so it is thrown out before anyone asks for it, and when they finally do it is already gone. By reordering the lib link order you're putting the consumers ahead of the producers. `http`, `core` and `utils` say they need a `VAR`, but haven't seen it yet, so the linker stays on the lookout for it, and eventually finds it when bringing `config` into the party wiring the fix-ups as warranted. – WhozCraig Oct 25 '22 at 04:49
  • In short, this isn't as much a cmake thing as it is a `ld` thing (or so has been my experience; other can, and no-doubt-will, chime in). General rule: always provide your libs in your link line in the order of most-dependent to least-dependent, top to bottom. The libs depending on other libs should be first, the ones dependent on near-nothing and only providing dependencies to the libs prior should be at the bottom. – WhozCraig Oct 25 '22 at 04:50
  • Better would be to declare the dependencies correctly, so that CMake knows http, core, and utils depend on config. That way, the order given in `target_link_libraries` won't matter. – Alex Reinking Oct 25 '22 at 05:03
  • Thank you for explaining and give me the better approach guys. help a lot – Fikra Laksana Putra Oct 25 '22 at 05:18
  • Ordering of the linked libraries is described in [that answer](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/24675715#24675715) to the duplicate question. – Tsyvarev Oct 25 '22 at 08:07

0 Answers0