main.c主要实现通过 curl 取回http://www.csdn.net/ 的首页并写入curl-test 文件中,实现如下:
#include "curl.h"
#include
#include
#include
FILE *fp;
int write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
int written = fwrite(ptr, size, nmemb, (FILE *)fp);
return written;
}
int main()
{
const char * path = "curl-test";
const char * mode = "w";
fp = fopen(path,mode);
curl_global_init(CURL_GLOBAL_ALL);
CURLcode res;
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://www.csdn.net/");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
在这个功能的实现过程中,主要是需要导入第三方库,curl
主CMakeLists.txt内容如下:
PROJECT(CURLTEST)
ADD_SUBDIRECTORY(src bin)
src/CMakeLists.txt内容如下:
ADD_EXECUTABLE(curltest main.c)
MESSAGE("DIR:"${CMAKE_SOURCE_DIR}/thirdparty/curl/include)
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/thirdparty/curl/include)
TARGET_LINK_LIBRARIES(curltest ${CMAKE_SOURCE_DIR}/thirdparty/curl-7.28.0/l
定义cmake/FindCURL.cmake
FIND_PATH(CURL_INCLUDE_DIR curl.h ${CMAKE_SOURCE_DIR}/thirdparty/curl-7.28.
FIND_LIBRARY(CURL_LIBRARY libcurl.a ${CMAKE_SOURCE_DIR}/thirdparty/curl-7.2
IF (CURL_INCLUDE_DIR AND CURL_LIBRARY)
SET(CURL_FOUND TRUE)
ENDIF (CURL_INCLUDE_DIR AND CURL_LIBRARY)
IF (CURL_FOUND)
IF (NOT CURL_FIND_QUIETLY)
MESSAGE(STATE "FOUND CURL_LIBRARY:${CURL_LIBRARY}" )
ENDIF(NOT CURL_FIND_QUIETLY)
IF(CURL_FIND_REQUIRED)
MESSAGE(FATAL_ERROR "can not find curl lib")
ENDIF(CURL_FIND_REQUIRED)
ENDIF(CURL_FOUND)
前面的 CURL 例子中我们使用了最简单的 FIND_PACKAGE 指令,其实他可以使用多种参数,
QUIETLY参数,对应与我们编写的FindCURL中的 CURL_FIND_QUIETLY,如果不指定 这个参数,就会执行:
MESSAGE(STATUS "Found CURL: ${CURL_LIBRARY}")
REQUIRED 参数,其含义是指这个共享库是否是工程必须的,如果使用了这个参数,说明这 个链接库是必备库,如果找不到这个链接库,则工程不能编译。对应于 FindCURL.cmake模块中的 CURL_FIND_REQUIRED变量。
同样,我们在上面的模块中定义了 CURL_FOUND, CURL_INCLUDE_DIR,CURL_LIBRARY 变量供开发者在 FIND_PACKAGE 指令中使用。
主CMakeLists.txt内容如下:
SET(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake)
MESSAGE("CMAKE_MODULE_PATH:${CMAKE_MODULE_PATH}")
PROJECT(CURLTEST)
ADD_SUBDIRECTORY(src bin)
src/CMakeLists.txt内容如下:
FIND_PACKAGE(CURL)
IF(CURL_FOUND)
ADD_EXECUTABLE(curltest main.c)
INCLUDE_DIRECTORIES(${CURL_INCLUDE_DIR})
TARGET_LINK_LIBRARIES(curltest ${CURL_LIBRARY})
ENDIF(CURL_FOUND)
FIND_系列指令主要包含一下指令: FIND_FILE( name1 path1 path2 ...)
VAR 变量代表找到的文件全路径,包含文件名 FIND_LIBRARY( name1 path1 path2 ...)
VAR 变量表示找到的库全路径,包含库文件名 FIND_PATH( name1 path1 path2 ...)
VAR 变量代表包含这个文件的路径。 FIND_PROGRAM( name1 path1 path2 ...)
VAR 变量代表包含这个程序的全路径。
FIND_PACKAGE( [major.minor] [QUIET] [NO_MODULE]
[[REQUIRED|COMPONENTS] [componets...]])
用来调用预定义在 CMAKE_MODULE_PATH 下的 Find