简体   繁体   中英

How to include files in a subdirectory of a CMake project, without using another CMakeLists.txt

I have a project added as a submodule to another project using CMake. The submodule is just two files ( bc , bh ) so the project structure is:

root/
 | CMakeLists.txt
 | main.cc
 | a.cc
 | a.h
 | submodule/
 |   |  b.c
 |   |  b.h

I don't want to add another CMakeLists.txt to the submodule as it's just another git thing to maintain. The submodule will never grow beyond these two files so I just want something simple and CMake is overkill for some of my other projects, so I don't want it in the submodule's git repo.

If I try include_directories(submodule) and add submodule/bc to the sources list of my add_executable block, I get undefined references to the functions inside bc/h

Is there a quick and simple way to just add these extra files to the sources without getting undefined references? Or is there a better way of managing this tiny library?

I have

include_directories(${PROJECT_SOURCE_DIR}/submodule)

...

add_executable(${NAME}
    submodule/b.c
    main.cpp
    server.cc
)

I have also tried adding

target_link_directories(${NAME} PUBLIC 
    ${PROJECT_SOURCE_DIR}/submodule
)

The error is:

/usr/lib/gcc/arm-none-eabi/10.3.1/../../../arm-none-eabi/bin/ld: CMakeFiles/light.dir/
server.cc.obj: in function `tcpRecvCallback(void*, tcp_pcb*, pbuf*, signed char) [clon
e .part.0]':
server.cc:(.text._Z15tcpRecvCallbackPvP7tcp_pcbP4pbufa.part.0+0x62): undefined referen
ce to `http_req_parse(char*)'
collect2: error: ld returned 1 exit status
gmake[2]: *** [CMakeFiles/light.dir/build.make:3083: light.elf] Error 1
gmake[1]: *** [CMakeFiles/Makefile2:1520: CMakeFiles/light.dir/all] Error 2
gmake: *** [Makefile:156: all] Error 2                    

where server.cc is in the project root, and http_req_parse is a function in bc

main.cpp includes server.h which includes submodule/bh

It may be relevant that I am building for a raspberry pi pico W.

new answer:

include_directories(${PROJECT_SOURCE_DIR}/submodule)

set(SOURCES submodule/b.c)

add_executable(${PROJECT_NAME} SOURCES)

old answer:

include_directories(${PROJECT_SOURCE_DIR}/submodule)

file(GLOB submodule_source submodule/*.c)

add_executable(${PROJECT_NAME} submodule_source)

It turns out that all the above answers were correct, I was forgot to use the language specific guards, since my library was in C, and my project was in C++.

IE, I didn't have

#ifdef _cplusplus
extern "C" {
#endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM