最近在做一个 sdk 接入的工作,将 sdk 接入到另外一个 App 中,但是接入时需要改写 App 使用的某个库 L,而 L 库同时被多个 App 引用,所以,我的改写必须对其他 App 不产生影响,所以想到了通过预编译宏的方式,保留原有类和接口的同时,让定义了宏的 App 端可以使用新的 sdk。现在的问题就是,如何添加宏定义,让当前 App 端满足
日常工作中,预编译宏我们常常遇到,比如下面几个,你一定遇到过:
#ifdef __OBJC__
#import "xxxxx.h"
#endif
or
#ifdef DEBUG
#define REMOTE_API_URL @"xxxxxxxxxxx"
#endif
or
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
预编译指令
预编译阶段预编译器能识别的指令,一般以#开头。
常用的如:
// 文件包含
#include
#import
// 宏定义
#define
// 条件编译
#if #else #endif
#ifdef #else #endif
#ifndef #else #endif
// 错误、警告处理
#error
#warning
// 编译器控制
#pragma
// 其他
#line
条件编译预编译指令完全可以满足控制代码是否生效的需求,但是,如何设置预编译宏定义呢?下面研讨几个方法。
修改 Target 的Build Setting
最先想到的方法,可以对整个 App 生效,如果你从网上搜索,会搜出一顿文章讲述这样的步骤。设置位置如下图:
但是,对于通过 CocoaPods 管理的项目,这一步骤只会对主工程生效,而对于 Pods 下的自工程,是不会生效的。所以,并不能解决本人上面提出的问题。
添加 pch 文件
prefix compile header文件,即我们常说的 pch 文件,预编译器会自动查找这样的文件并预处理加入到配置中的 pch 文件,实现一些预处理工作。
可以尝试一下,同样,
Podfile Hook
这个方法是在同事的提醒下操作完成的,完美解决了本人的问题。
通过 Podfile 的 Hook 功能,给 Pods 项目下的某个 target 预定义宏
http://stackoverflow.com/questions/27133993/why-isnt-my-cocoapods-post-install-hook-updating-my-preprocessor-macros
在Podfile末尾添加下面语法,给XXXXXX这个pod下的target预定义全局宏HELLO_MACRO
// ...
post_install do |installer_representation|
installer_representation.pods_project.targets.each do |target|
puts "===================>target name #{target.name}"
if target.name == 'XXXXXX'
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)','HELLO_MACRO']
puts "===================>target build configure #{config.build_settings}"
end
end
end
end
最后,Enjoy yourself!