Namespace exercise - Compiler Error?

Hello, I'm trying to complete an assignment that demonstrates namespaces. I have read the book and searched online, and cannot figure out why this won't compile. I have 2 header files, 2 files containing function definitions for the associated header files, and a main program. The compiler is giving 2 errors from main.cpp:

main.cc: undefined reference to 'A::f(void)'
main.cc: undefined reference to 'A::g(void)'

Here is the code for main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include "f.h"
#include "g.h"

using std::cout;
using std::endl;

int main()
{
	cout << "Namespace experiment initialized." << endl;
	
	{
		using namespace A;
		A::f();
		A::g();
	}

	return 0;
}


Here is the code for f.h:
1
2
3
4
namespace A
{
	void f();
}


Here is the code for g.h:
1
2
3
4
namespace A
{
	void g();
}


Here is the code for f.cpp:
1
2
3
4
5
6
7
8
9
void f()
{
	cout << "Function f called." << endl;
}

void g()
{
	cout << "Function g called." << endl;
}


Here is the code for g.cpp:
1
2
3
4
5
6
7
8
9
void f()
{
	cout << "Function f called." << endl;
}

void g()
{
	cout << "Function g called." << endl;
}
Last edited on
Your (multiple) definitions of f and g do not reside in the namespace A.

Your compiler (or more accurately, linker) is perfectly correct in complaining that it can't find the definition of those functions.

[edit:]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>

namespace A
{
    void f() 
    {
        std::cout << "A::f()\n";
    }

    void g();
    void h();
}

// One way to define a function in a namespace:
void A::g()
{
    std::cout << "A::g()\n";
}

// Another:
namespace A
{
    void h()
    {
        std::cout << "A::h()\n";
    }
}

int main()
{
    // f(); // illegal, no function named f in scope.

    A::f();
    A::g();
    A::h();

    using namespace A;
    f();
    g();
    h();
}
Last edited on
Topic archived. No new replies allowed.