nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 C++ (Part 11: C/C++/ObjC混合编程) #241

Open nonocast opened 2 years ago

nonocast commented 2 years ago

Overview

C++调用C

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)

Objective-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

C和Objective-C

foo.h

#ifndef FOO_H
#define FOO_H

void hello();

#endif

foo.m

#import <Foundation/Foundation.h>

void hello() {
  NSLog(@"Hello, World!");
}

main.cpp

extern "C" {
#include "foo.h"
}

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

CMakeLists.txt

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就好。

参考文档