c语言 - 为什么这个 CMake 不编译?



我被困在一个没有编译的CMake项目中。我在一个简单的测试项目中隔离了这个问题。它由一个文件teste(主)和libs/子目录中的一个库组成。测试非常简单:main调用lib中的一个函数。编译器生成的是.c.o编译文件,而不是.o编译文件。CMake生成的Makefile,但当我运行使它编译ok,但在链接阶段,它给我:

make
Consolidate compiler generated dependencies of target testecompila
[ 50%] Linking C executable bin/testecompila
/usr/bin/ld: CMakeFiles/testecompila.dir/teste.c.o: na função "main":   <=== .c.o file
teste.c:(.text+0x19): referência não definida para "testeint" <=== the libs fct I call in main
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/testecompila.dir/build.make:97: bin/testecompila] Erro 1
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/testecompila.dir/all] Erro 2
make: *** [Makefile:91: all] Erro 2

目录树:

.    ===> testcompila dir
├── libs
│   ├── bin 
│   │    └── Makefile       ==>>> Generated from CMake
│   ├── include
│   │   └── testelib.h
│   └── src
│       ├── CMakeLists.txt
│       └── testelib.c
└── src
├── bin 
│    └── Makefile       ==>>> Generated from CMake
├── CMakeLists.txt
└── teste.c

test.c:

#include "stdio.h"
#include "testelib.h"
int main(int argc, char** argv)
{
return testeint();
}

testelib.h:

int testeint();

testelib.c:

#include "testelib.h"
int testeint()
{
int C = 0;
C++;
return C;
}

teste.c:

#include "stdio.h"
#include "testelib.h"
int main(int argc, char** argv)
{
return testeint();
}

CMakeLists from ./src

####################
#      Global      #
####################
cmake_minimum_required(VERSION 3.12)
#set(CMAKE_CXX_STANDARD 17)
#####################
#      Project      #
#####################
# Project variables
set(LOCAL_PROJECT_NAME        "testecompila")
set(LOCAL_PROJECT_VERSION     "0.0.1")
set(LOCAL_PROJECT_DESCRIPTION "Teste compilação")
# Source files (relative to "src" directory)
set(SOURCES
teste.c
)
# Compiler definitions
set(DEFINES
)
# Compiler options
set(OPTIONS
)
# Project setup
project(${LOCAL_PROJECT_NAME}
VERSION ${LOCAL_PROJECT_VERSION}
DESCRIPTION ${LOCAL_PROJECT_DESCRIPTION}
LANGUAGES C)

add_executable(${LOCAL_PROJECT_NAME} teste.c)
list(TRANSFORM HEADERS PREPEND "../include/")
list(TRANSFORM SOURCES PREPEND "../src/")

INCLUDE_DIRECTORIES(../libs/include/)
message ("======>" ${LOCAL_PROJECT_NAME})
set_target_properties(${LOCAL_PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "bin")
set_target_properties(testecompila PROPERTIES LINKER_LANGUAGE C)
target_include_directories(testecompila PUBLIC ${PROJECT_BINARY_DIR})
####################
#   Dependencies   #
####################

CMakeLists.txt from ./libs/src

cmake_minimum_required(VERSION 3.23)    
project(libteste)
add_library(libteste STATIC testelib.c)
SET_SOURCE_FILES_PROPERTIES(testelib.c PROPERTIES LANGUAGE C)
INCLUDE_DIRECTORIES(/usr/include )
set(CMAKE_EXE_LINKER_FLAGS --verbose)

我在VM Oracle VirtualBox上运行Ubuntu。

您需要告诉testecompila它使用libteste。试试target_link_libraries(${LOCAL_PROJECT_NAME} PUBLIC libtests).

最新更新