简体   繁体   中英

C++: ODR violation for member functions defined outside of class body but enclosed within header guard (as shown in YouCompleteMe plugin)

I have a simple header file as shown below.

  #ifndef PERSON_H
  #define PERSON_H

  #include <iostream>
  #include <string>
  using namespace std;

  struct Person {
      string name;
      string address;
      auto get_name() const -> string;
  };

 string Person::get_name() const {  // Function 'get_name' defined in a header file; function definitions in header files can lead to ODR violations
          return this -> name;
  }

  #endif

Question:
Even though the Person::get_name() function is defined outside of the struct Person, this function is defined inside the header guard PERSON_H. YouCompleteMe tool (presume using g++), it states it violates ODR. Why would it violates ODR? This function will never be defined more than once since it's control by header guard PERSON_H. I am not sure if there is a bug in the YouCompleteMe tool because i noticed i don't get the same warning message using visual studio.

Any help would be great.
Thanks.

It can be included in multiple compilation units. If you mark the definition inline it should be happy.

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