在CMake项目中从C ++调用C代码。未定义的符号。有外部C [英] Calling C code from C++ in a CMake project. Undefined symbol. Have extern C

查看:149
本文介绍了在CMake项目中从C ++调用C代码。未定义的符号。有外部C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图构建一个从C ++调用C代码的CMake项目,尽管我正确地使用了外部C(AFAIK),但我却得到了未定义的符号。

I'm trying to build a CMake project that calls C code from C++, and I'm getting undefined symbols, even though I'm (AFAIK) properly using "extern C".

CMakeLists.txt:

CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)
project(CTest LANGUAGES CXX)
add_executable(test main.cpp lib.c)

main.cpp:

#include "lib.h"

int main()
{
    printit();
    return 0;
}

lib.c:

#include <stdio.h>
#include "lib.h"

int printit()
{
    printf("Hello world\n");
    return 0;
}

lib.h:

extern "C" int printit();

这给了我一个未定义引用printit的错误。

That gives me an "undefined reference to printit" error.

如果我只是从命令行构建它,它就可以正常工作:

If I simply build this from the command-line, it works fine:

g++ main.cpp lib.c

我在做什么错了?

推荐答案

外部 C 是C ++语法。因此,您的标头lib.h不能在C中使用。如果按以下方式进行更改,那么它也可以在C ++和C中使用。

extern "C" is C++ syntax. Your header lib.h therefore cannot be used from C. If you change it as follows it can be used from C++ and C as well.

#ifndef LIB_H_HEADER
#define LIB_H_HEADER

#ifdef __cplusplus
extern "C" 
{
#endif

int printit();

#ifdef __cplusplus
}
#endif

#endif /* LIB_H_HEADER */

由于同时具有C和CXX源,因此您的项目调用也应启用C project(CTest语言C CXX)在您的CMakeLists.txt中。

As you have both C and CXX sources your project call should enable C as well project(CTest LANGUAGES C CXX) in your CMakeLists.txt.

这篇关于在CMake项目中从C ++调用C代码。未定义的符号。有外部C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆