Open nonocast opened 2 years ago
calc.h
#ifndef CALC_H #define CALC_H int add(int a, int b); #endif
calc.c
#include "calc.h" int add(int a, int b) { return a + b; }
main.cpp
extern "C" { #include "calc.h" } #include <iostream> int main() { std::cout << add(1, 2) << std::endl; return 0; }
方法1: 通过gcc/g++分别编译和链接。
➜ gcc -c calc.c -o calc.o ➜ g++ -c main.cpp -o main.o ➜ gcc calc.o main.o -lstdc++ -o app
方法2: 交给cmake自己弄。
cmake_minimum_required(VERSION 3.10) project(mix) add_executable(app main.cpp calc.c)
app.m
#import <Foundation/Foundation.h> int main() { NSLog(@"Hello, World!"); return 0; }
CMakeLists.txt
cmake_minimum_required(VERSION 3.10) project(hello) find_library(COREFOUNDATION CoreFoundation) find_library(COCOA Cocoa) include_directories(${COREFOUNDATION} ${COCOA}) add_executable(app app.m) target_link_libraries(app ${COREFOUNDATION} ${COCOA})
如果是命令行: gcc -framework Foundation -x objective-c app.m -o app
gcc -framework Foundation -x objective-c app.m -o app
foo.h
#ifndef FOO_H #define FOO_H void hello(); #endif
foo.m
#import <Foundation/Foundation.h> void hello() { NSLog(@"Hello, World!"); }
extern "C" { #include "foo.h" } int main() { hello(); return 0; }
cmake_minimum_required(VERSION 3.10) project(mix) find_library(COREFOUNDATION CoreFoundation) find_library(COCOA Cocoa) include_directories(${COREFOUNDATION} ${COCOA}) add_executable(app main.cpp foo.m) target_link_libraries(app ${COREFOUNDATION} ${COCOA})
结论: 交给CMake就好。
Overview
C++调用C
calc.h
calc.c
main.cpp
方法1: 通过gcc/g++分别编译和链接。
方法2: 交给cmake自己弄。
Objective-C
app.m
CMakeLists.txt
如果是命令行:
gcc -framework Foundation -x objective-c app.m -o app
C和Objective-C
foo.h
foo.m
main.cpp
CMakeLists.txt
结论: 交给CMake就好。
参考文档