首页 > 解决方案 > 如何在 C 中编写翻译单元?

问题描述

基本上我想要做的是C等价于:

翻译单元列表.cpp

std::vector<std::string> list;
bool addListItem(std::string str){
    list.push_back(str);
    return true;
}
int main(int argc, char **argv){
  for(std::string translation_unit_name : list){
    cout << translation_unit_name << endl;
  }
  return 0;
}

一些文件.cpp

static bool initialized = addListItem("some file!");

some_file2.cpp

static bool initialized = addListItem("some other file!");

这样,translation_unit_list 就知道编译成最终可执行文件的每个翻译单元。这允许用户有选择地编译他们想要包含的内容。有没有办法用c实现相同的结果?

示例所需的行为:

g++ -o exec1 translation_unit_list.cpp some_file.cpp 
./exec1
some file!

g++ -o exec1 translation_unit_list.cpp some_file2.cpp 
./exec1
some other file!

g++ -o exec1 translation_unit_list.cpp some_file.cpp some_file2.cpp 
./exec1
some file!
some other file!

标签: c++cgccvisual-c++clang

解决方案


推荐阅读