C/C++: Full example of using C code in a C++ project


The following set of code present a fully functioning example of using a simple C library as part of a CPP based project to print on screen.

[download id=”2434″]

The trick relies on encapsulating the C header definitions in the extern "C" declaration. extern "C" will make all function and variable names in C++ have C linkage. What this means at the compiler level is that the compiler will not modify the names so that the C code can link to them and use them using a C compatible header file containing just the declarations of your functions and variables.

[download id=”2434″]

main.c

#include "cpp_library.h"
#include "c_library.h"

extern "C" void c_hello_world();

int main() {

    cpp_hello_world();
    c_hello_world();
    return 0;
}

cpp_library.h

#ifndef CPP_BASE_CPP_LIBRARY_H
#define CPP_BASE_CPP_LIBRARY_H

void cpp_hello_world();

#endif //CPP_BASE_CPP_LIBRARY_H

cpp_library.cpp

#include <iostream>
#include "cpp_library.h"

void cpp_hello_world() {

    std::cout << "Hello, World!" << std::endl;
}

c_library.h

#ifndef CPP_BASE_C_LIBRARY_H
#define CPP_BASE_C_LIBRARY_H

#ifdef __cplusplus
extern "C" {
#endif

void c_hello_world();

#ifdef __cplusplus
}
#endif

#endif //CPP_BASE_C_LIBRARY_H

c_library.c

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

void c_hello_world() {

    printf("Hello, World!\n");
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(CPP_Base)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp cpp_library.cpp cpp_library.h c_library.c c_library.h)
add_executable(CPP_Base ${SOURCE_FILES})

[download id=”2434″]

This post is also available in: Αγγλικα

Απάντηση

Αυτός ο ιστότοπος χρησιμοποιεί το Akismet για να μειώσει τα ανεπιθύμητα σχόλια. Μάθετε πώς υφίστανται επεξεργασία τα δεδομένα των σχολίων σας.