OC/C/C++入口函數獲取命令行傳入的參數

OC

  1. 新建 MacApp
  2. 修改main.m ,不需要運行循環便直接return 0 了事

測試代碼如下:

int main(int argc, const char * argv[]) {
    //MacApp的編譯產物中找到可執行文件 Mac.app/Contents/MacOS/MacApp -o "hello world"
    NSString *arg = [[NSUserDefaults standardUserDefaults] stringForKey:@"o"];
    NSLog(@"OC打印: %@",arg);
    printf("C打印: %s\n",[arg UTF8String]);
    return 0;
}

然後直接 + B 編譯一下,然後找到編譯產物目錄下的可執行文件(一般在~/Library/Developer/Xcode/DerivedData該路徑下找快一些)

C/C++

  1. 創建一個命令行項目即可
  2. 代碼如下:
#include <iostream>

using namespace std;

int main(int argc, const char * argv[]) {
    // gcc main.cpp -lstdc++ -o  helloworld   #編譯
    //./helloworld "hhh" "ggg" "123" "jk666"  #調用
    cout << argv[0] << endl;// ./helloworld
    cout << argv[1] << endl;// hhh
    cout << argv[2] << endl;// ggg
    cout << argv[3] << endl;// 123
    cout << argv[4] << endl;// jk666
        
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章