我正在尝试使用计算给定数字的斐波那契的示例项目来学习 CMake。我的项目最初包含一个“.c”文件和标题。我能够使用 CMake 构建并毫无问题地运行。现在我正在尝试通过将我的 fibnoacci 函数移动到一个单独的“.c”文件中来学习如何链接库,我使用 CMake 将其编译成一个可链接库。它可以毫无问题地构建,但在我运行它时会引发分段错误。我的项目结构是:
fib
|
*---MathFunctions
| |
| *----CMakeLists.txt
| |
| *----myfib.h
|
*---CMakeLists.txt
|
*---fib.c
|
*---fib.h
|
*---myfib.c
|
*---Config.in.h
MathFunctions 文件夹下的 CMakeLists.txt 为空。所有的程序逻辑都在 fib.c 和 myfib.c 中。所有构建都在顶部 CMakeLists.txt
编者按:
# include "stdio.h"
# include "stdlib.h"
# include "Config.h"
#include "myfib.h"
void internalfib(int num)
{
printf("Internally defined fib\n");
int a, b;
a = 0;
b = 1;
printf( "custom fib of %d", b );
for( int i = 0; i + a <= num; b = i ) {
i = a + b;
a = b;
printf( ", %d", i );
}
}
int main( int argc, char** argv) {
fprintf(stdout,"%s Version %d.%d\n",
argv[0],
VERSION_MAJOR,
VERSION_MINOR);
#ifdef SHOW_OWNER
fprintf(stdout, "Project Owner: %s\n", OWNER);
#endif
myfib(atof( argv[1] ));
printf("\n");
return EXIT_SUCCESS;
}
myfib.c:
# include "stdio.h"
# include "stdlib.h"
void myfib(int num)
{
printf("custom myfib");
int a, b;
a = 0;
b = 1;
printf( "custom fib of %d", b );
for( int i = 0; i + a <= num; b = i ) {
i = a + b;
a = b;
printf( ", %d", i );
}
}
CMakeLists.txt:
#Specify the version being used aswell as the language
cmake_minimum_required(VERSION 2.6)
#Name your project here
project(fibonacci)
enable_testing()
set (VERSION_MAJOR 1)
set (VERSION_MINOR 0)
configure_file (
"${PROJECT_SOURCE_DIR}/Config.h.in"
"${PROJECT_BINARY_DIR}/Config.h"
)
option (SHOW_OWNER "Show the name of the project owner" ON)
#Sends the -std=c99 flag to the gcc compiler
add_definitions(-std=c99)
include_directories("${PROJECT_BINARY_DIR}")
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions)
add_library(MathFunctions myfib.c)
#This tells CMake to fib.c and name it fibonacci
add_executable(fibonacci fib.c)
target_link_libraries (fibonacci MathFunctions)
#test that fibonacci runs
add_test (FibonacciRuns fibonacci 5)
#Test the fibonacci of 5
add_test (FibonacciCompare5 fibonacci 5)
set_tests_properties (FibonacciCompare5 PROPERTIES PASS_REGULAR_EXPRESSION "1, 1, 2, 3, 5")
install (TARGETS fibonacci DESTINATION ${PROJECT_BINARY_DIR}/bin)
从构建文件夹运行“..cmake”和“make”后,我运行:
~/dev/cworkshop/fib/build$ ./fibonacci
./fibonacci Version 1.0
Project Owner: Clifton C. Craig
Segmentation fault: 11
我哪里错了?