Calling C code from C++ in a CMake project. Undefined symbol. Have extern C

£可爱£侵袭症+ 提交于 2020-07-16 10:29:47

问题


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:

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();

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

What am I doing wrong?


回答1:


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 */

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.



来源:https://stackoverflow.com/questions/54280003/calling-c-code-from-c-in-a-cmake-project-undefined-symbol-have-extern-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!