Local class name conflict
Andrew Pinski
pinskia@gmail.com
Tue Jan 16 06:46:00 GMT 2018
On Mon, Jan 15, 2018 at 10:35 PM, chenzhelu <chenzero@netease.com> wrote:
> Hello all,
> I encountered a problem on "local class name conflict",
> I searched on net and found that years ago, some people also encoutered this kind of problem.
The correct name for this is One Definition Rule (or ODR for short).
Basically a violation of this rule causes the code to be invalid (with
no diagnostic required; therefor undefined code). If you use LTO, GCC
sometimes will warn about this violation.
If you want a truly local class, then use anonymous namespaces which
is designed to fix this issue.
Thanks,
Andrew
>
> https://stackoverflow.com/questions/10671956/same-class-name-in-different-c-files
> http://www.cplusplus.com/forum/general/32010/
>
>
> Please see the following code, (BTW, it seems that the maillist can not attach files)
>
> When I ran the code(Ubuntu 64bis, gcc vesion:5.4.0, the amazing result is :
> localClassXInData.cpp in Data.cpp
> localClassXInData.cpp in Data.cpp
>
>
> I think there is an error in Link phrase:
> 1. if comment out the LocalClassX definition in main.cpp, the compile will not compile the code --- this is as expected.
> 2. however, if run the code(not comment out any code), the code actually ran is in the Data.cpp, that is not consistent with compile phase.
>
>
> Thanks!
>
>
> code
> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> // main.cpp
>
> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> #include <stdio.h>
> #include <stdlib.h>
>
> #include <string>
> using namespace std;
>
> class LocalClassX
> {
> public:
> string name;
>
> LocalClassX() {
> name = "localClassXInMain.cpp" ;
> }
>
> virtual ~LocalClassX() {
> }
>
> virtual void f() {
> printf("%s in main.cpp \n ", name.c_str());
> }
> };
>
> #include "Data.h"
> Data data;
>
> int main(int argc, char* argv[])
> {
> try {
> LocalClassX x;
> x.f();
> data.add(1);
> }
> catch (...) {
> printf("error \n");
> return 1;
> }
> return 0;
> }
>
>
> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> // Data.h"
> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> #ifndef DataH
> #define DataH
>
> #include <vector>
> #include <string>
> using namespace std;
>
>
> class Data {
> protected:
> vector<int> data;
> public:
> Data();
> virtual ~Data();
>
> void add(int i);
> };
>
> #endif
>
>
> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> // Data.cpp
>
> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> #include <stdio.h>
>
> #include "Data.h"
>
> Data::Data()
> {
> }
> Data::~Data()
> {
> }
>
> class LocalClassX
> {
> public:
> string name;
>
> LocalClassX() {
> name = "localClassXInData.cpp" ;
> }
>
> virtual ~LocalClassX() {
> }
>
> virtual void f() {
> printf("%s in Data.cpp \n ", name.c_str());
> }
> };
>
> void Data::add(int i)
> {
> LocalClassX x;
> x.f();
>
> data.push_back(i);
> }
>
More information about the Gcc
mailing list