简体   繁体   中英

C++ undefined reference error

First, a more abstract question. Is it good practice to use a namespace instead of a class, in terms of speed, when you don't need a constructor/destructor or multiple copies of said object?

Second, I get " ccEaV3B0.o:main.cc:(.text+0x10): undefined reference to `board::arbi' " when trying to include and use a namespace. I'm using Mingw32 on Windows 7, with the make command: g++ -Wall main.cc board.cc

This also happens when I compile seperately, using: g++ -c board.cc g++ -Wall main.cc board.o

Here are the (minimal) files:

main.cc:

#include <iostream>
using namespace std;

#include "board.h"

int main(){
    cout << board::give() << endl;
    return 0;
}

board.h:

#ifndef BOARD_H
#define BOARD_H

namespace board {
    extern int arbi;
    extern int give();
}

#endif

board.cc:

#include "board.h"

int board::give(){
    return arbi;
}

Solved by giving an initialisation "int board::arbi = 5;" in board.cc

The question remains why you should use a class when something is clearly an object, even if you know there will always be exactly one instance of said object. It seems to me you would want globals, but to avoid name-clashing, you would put them in a namespace.

You have not defined board::arbi . That is likely your undefined reference.

As for namespace versus class , they serve different purposes. A class provides a set of properties for a group of objects that instantiate or derive from it. A namespace is a way to provide collection of symbols with a common prefix. It is not a scope (although namespace resolution sort of works like a scope), and there is no inheriting or deriving from a namespace .

A scope has the ability to restrict visibility of a name that is inside it. A namespace does not provide any visibility hiding beyond what is available for regular variables (eg file static variables). Where as a class can create private or protected data members and methods.

You need to define board::arbi in the board.cc file.

 int board::arbi = <whatever initial value>;

With the extern declaration you only comforted the compiler that you will provide the definition later, but you didn't provide one.

Regarding the abstract question, the concept of class and namespace is very different. Class defines structure for objects which are 'real'. i,e,they occupy memory. Namespace is just like a fence restricting the scope of global variables. They don't occupy memory.... So, if you see logical objects in your program define them as classes. But, if you see only a set of global functions which are somehow related, but you can't imagine them as a coherent object, use namespace.

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