简体   繁体   中英

why is struct definition on header file? (cpp)

i am newbie.

i am analyzing some open source code, but it's hard to me.

i saw struct definition(maybe) on header file.

but as i know, header file is just for declaration and it's Implementation file for definition.

i only find header file's definition(maybe, because i can't find definition!)

struct NativeModule {
  std::unordered_set<uint64_t> exported_vars;
  std::unordered_set<uint64_t> exported_funcs;

  SegmentMap segments;

  std::unordered_map<uint64_t, std::unique_ptr<NativeFunction>> ea_to_func;

  std::unordered_map<std::string, const NativeExternalFunction *>
      name_to_extern_func;

  // Represent global and external variables.
  std::unordered_map<uint64_t, std::unique_ptr<NativeVariable>> ea_to_var;
  std::unordered_map<std::string, const NativeExternalVariable *>
      name_to_extern_var;

  NativeFunction *TryGetFunction(uint64_t ea) const;
  NativeVariable *TryGetVariable(uint64_t ea) const;

  std::vector<std::unique_ptr<NativeVariable>> dead_vars;
};

source code is here

if you explain to me. thank you.

First note that all definitions are also declarations , but not the other way around.

What you are showing here is a definition of the class type NativeModule , but only declarations of the member functions TryGetFunction and TryGetVariable .

A program may have multiple definitions of a class, as long as each definition appears in a different translation unit and all are practically identical (same token sequence plus other requirements). This is why it is allowed and good practice to put class definitions that are supposed to be shared between translation units into header files.

The same is true for inline (member) functions. A function is inline if it is declared with the inline keyword or if its definition is put directly into the class definition. This is not the case here for the two functions mentioned above, they are only declared in the class definition.

Non-inline functions may have only one definition in the whole program , which is why their definitions cannot be put in header files (if they have external linkage) and instead only a declaration is put in the header file and the definition is put in one source file. The same is true for non-inline static storage duration variables.

So the functions TryGetFunction and TryGetVariable will need to be defined somewhere in one of the source files. By convention it should be the source file with the same name as the header containing the class, but ending in .cpp or one of the other common C++ source file extensions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM