jeudi 18 avril 2019

Is it possible to #include a namespaced class into another namespace

I am working through Bjarne Stroustrup's "The C Programming Language (4th edition)" and I came across an example in section 14.4.6 (Namespaces - Versioning) that I haven't been able to replicate. The example #includes a namespaced class declaration into another namespace. Here is my simplified attempt at reproducing this example:

// V3.h

namespace V3 {
    class C {
        public:
            void print();
    };
}

// V3.cpp

#include <iostream>
#include "V3.h"

using namespace std;

namespace V3 {
    void C::print() {
        cout << "Hello from C" << endl;
    }
}

// Popular.h

namespace Popular {
    #include "V3.h"
}

// main.cpp

#include "Popular.h"

int main() {
    Popular::V3::C c;
    c.print();
}

When I attempt to compile this program I get the following output:

$ g++ main.cpp V3.cpp
/tmp/ccAVnUZi.o: In function `main':
main.cpp:(.text+0x1f): undefined reference to `Popular::V3::C::print()'
collect2: error: ld returned 1 exit status

Thus, I'm wondering, is it possible to #include a namespaced class into another namespace? Or am I failing to reproduce this example for other reasons? I read in a later section (15.2.5) that it may not be possible to do this.

Aucun commentaire:

Enregistrer un commentaire