提问者:小点点

在CMake项目中从C++调用C代码。 未定义的符号。 具有外部C


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

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引用”错误。

如果我只是简单地从命令行构建它,它可以很好地工作:

g++ main.cpp lib.c

我做错了什么?


共1个答案

匿名用户

外部“C”是C++语法。 因此,标题lib.h不能从C中使用。如果您按如下方式更改它,它也可以从C++和C中使用。

#ifndef LIB_H_HEADER
#define LIB_H_HEADER

#ifdef __cplusplus
extern "C" 
{
#endif

int printit();

#ifdef __cplusplus
}
#endif

#endif /* LIB_H_HEADER */

因为您有C和CXX源,所以您的项目调用应该在您的cmakelists.txt中启用C以及project(CTest LANGUAGES C CXX)

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(cmake|项|目中|c++|调用|c|代码|未定义|符号|外部|c)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?