字典用例

这是在 CMake 中构建包含字典模块的例子。通过 find_package 手动添加 ROOT,而非使用 ROOT 建议的标志。在大多数系统中,CMake 文件中唯一重要的标志。

examples/root-dict/CMakeLists.txt

  1. cmake_minimum_required(VERSION 3.4...3.21)
  2. project(RootDictExample LANGUAGES CXX)
  3. set(CMAKE_CXX_STANDARD 11 CACHE STRING "C++ standard to use")
  4. set(CMAKE_CXX_STANDARD_REQUIRED ON)
  5. set(CMAKE_CXX_EXTENSIONS OFF)
  6. set(CMAKE_PLATFORM_INDEPENDENT_CODE ON)
  7. find_package(ROOT 6.20 CONFIG REQUIRED)
  8. # If you want to support <6.20, add this line:
  9. # include("${ROOT_DIR}/modules/RootNewMacros.cmake")
  10. # However, it was moved and included by default in 6.201
  11. root_generate_dictionary(G__DictExample DictExample.h LINKDEF DictLinkDef.h)
  12. add_library(DictExample SHARED DictExample.cxx DictExample.h G__DictExample.cxx)
  13. target_include_directories(DictExample PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")
  14. target_link_libraries(DictExample PUBLIC ROOT::Core)
  15. ## Alternative to add the dictionary to an existing target:
  16. # add_library(DictExample SHARED DictExample.cxx DictExample.h)
  17. # target_include_directories(DictExample PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")
  18. # target_link_libraries(DictExample PUBLIC ROOT::Core)
  19. # root_generate_dictionary(G__DictExample DictExample.h MODULE DictExample LINKDEF DictLinkDef.h)

支持文件

这是一个极简的类定义,只有一个成员函数:

examples/root-dict/DictExample.cxx

  1. #include "DictExample.h"
  2. Double_t Simple::GetX() const {return x;}
  3. ClassImp(Simple)

examples/root-dict/DictExample.h

  1. #pragma once
  2. #include <TROOT.h>
  3. class Simple {
  4. Double_t x;
  5. public:
  6. Simple() : x(2.5) {}
  7. Double_t GetX() const;
  8. ClassDef(Simple,1)
  9. };

还需要一个 LinkDef.h

examples/root-dict/DictLinkDef.h

  1. // See: https://root.cern.ch/selecting-dictionary-entries-linkdefh
  2. #ifdef __CINT__
  3. #pragma link off all globals;
  4. #pragma link off all classes;
  5. #pragma link off all functions;
  6. #pragma link C++ nestedclasses;
  7. #pragma link C++ class Simple+;
  8. #endif

进行测试

这是一个宏示例,用于测试上面文件生成的结果是否正确。

examples/root-dict/CheckLoad.C

  1. {
  2. gSystem->Load("libDictExample");
  3. Simple s;
  4. cout << s.GetX() << endl;
  5. TFile *_file = TFile::Open("tmp.root", "RECREATE");
  6. gDirectory->WriteObject(&s, "MyS");
  7. Simple *MyS = nullptr;
  8. gDirectory->GetObject("MyS", MyS);
  9. cout << MyS->GetX() << endl;
  10. _file->Close();
  11. }