-1

好吧,我厌倦了寻找问题,所以我想现在是时候问了 :) 在我描述问题之前,我的项目在 Visual 2013 上运行良好,但在 suse linux g++ 4.6.2 上运行良好

我们假设使用一个库 cio,它由三个文件 console.h、console.cpp 和 keys.h 组成。使用三个文件的主程序称为happy.cpp。

现在在 Visual Studio 2013 上一切正常。但是当我尝试在 linux 上编译时,它给了我很多错误。

以下是项目的简要代码说明

//console.h
namespace cio {

// Console holds the state of the Console Input Output Facility
//
class Console {
    //some varialbes and functions
    int   getRows() const;
};

extern Console console; // console object - external linkage

} // end namespace cio

===============================================================================
//console.cpp
/* table of platforms */
#define CIO_LINUX       1
#define CIO_MICROSOFT   2
#define CIO_BORLAND     3
#define CIO_UNIX        4

/* auto-select your platform here */
#if   defined __BORLANDC__
    #define CIO_PLATFORM CIO_BORLAND
    #define CIO_LOWER_LEVEL_H_ <conio.h>
#elif defined _MSC_VER
    #define CIO_PLATFORM CIO_MICROSOFT
    #include <windows.h>
    #define CIO_LOWER_LEVEL_H_ <conio.h>
#elif defined __MACH__
    #define CIO_PLATFORM CIO_UNIX
    #define CIO_LOWER_LEVEL_H_ <curses.h>
#elif defined __GNUC__
    #define CIO_PLATFORM CIO_LINUX
    #define CIO_LOWER_LEVEL_H_ <ncurses.h>
#elif !defined __BORLANDC__ && !defined _MSC_VER && !defined __GNUC__ && !defined __MACH__
    #error CONSOLE_PLT is undefined
#endif

extern "C" {
    #include CIO_LOWER_LEVEL_H_
}

#include "console.h"
#include "keys.h"

namespace cio { // continuation of cio namespace

// getRows retrieves the number of rows in the output object
//
int  Console::getRows() const {
    return bufrows;
}

} // end namespace cio
================================================================================
//////happy.cpp
 #include "console.h"
 #include "keys.h"    // for ESCAPE
 using namespace cio;

 int main() {
     int key, rows, columns;

     // get screen dimensions
     rows    = console.getRows();
 }

在使用“g++ happyface.cpp”命令编译时,出现以下错误

happyface.cpp:(.text+0xd): 未定义对cio::console' happyface.cpp:(.text+0x12): undefined reference tocio::Console::getRows()的引用

我不知道我在这里做错了什么?我还尝试包含路径“g++ -I ~/happy/console.h ~/happy/console.cpp ~/happy/keys.h”,但仍然是同样的问题。

4

3 回答 3

0
extern Console console; // console object - external linkage

确保它实际上是在某个地方定义的,例如在console.cpp. 我没有看到任何定义。

g++ -I ~/happy/console.h ~/happy/console.cpp ~/happy/keys.h

-I标志不应该是必需的。假设您的目录如下所示:

~/happy
 - console.h
 - console.cpp
 - keys.h
 - happyface.cpp

你应该能够做到

cd ~/happy
g++ console.cpp happyface.cpp -o happyface
./happyface
于 2013-09-24T20:20:53.373 回答
0

您在 console.h 中声明变量控制台为:

extern Console console;

但你还没有在任何地方定义它。

在 happy.cpp 中添加定义:

namespace cio {
Console console;
}

另一个明显的问题:您没有编译和链接 console.cpp 文件。'为了快速而肮脏的编译,你可以这样做:

g++ happyface.cpp console.cpp
于 2013-09-24T20:50:29.640 回答
0

您必须将每个翻译单元(又名.cpp文件)链接在一起。

编译使用g++ happyface.cpp console.cpp.

于 2013-09-24T20:19:08.517 回答