c++ - 外部错误 - undefined reference

标签 c++ c reference undefined extern

我正在尝试编译我的代码,但是当我这样做时,它发生了:

In function `main':
/home/emilio/CB/QAP/main.cpp|42|undefined reference to `start_timers()'
/home/emilio/CB/QAP/main.cpp|45|undefined reference to `elapsed_time()'

我有“timer.c”和“timer.h”作为外部函数来测量时间。

定时器.c

#include <stdio.h>
#include <time.h>
#include "timer.h"


clock_t start_time;
double elapsed;

void start_timers(){
    start_time = clock();
}

double elapsed_time( type )
TIMER_TYPE type;

{
    elapsed = clock()- start_time;
    return elapsed / CLOCKS_PER_SEC;
}

定时器.h

extern clock_t start_time;
extern double elapsed;

int time_expired();
void start_timers();
double elapsed_time();

typedef enum type_timer {REAL, VIRTUAL} TIMER_TYPE;

主要.cpp

#include "timer.h"
...
        double time;

        start_timers();
            launch_algorithm();;
        time = elapsed_time();
 ...

我该如何解决?谢谢!

最佳答案

您正在混合使用 C 和 C++。要在 C++ 文件中使用 C 的东西,你必须像这样包装标题

#ifdef __cplusplus
extern "C" 
{
#endif
    extern clock_t start_time;
    extern double elapsed;

    int time_expired();
    void start_timers();
    double elapsed_time();

    typedef enum type_timer {REAL, VIRTUAL} TIMER_TYPE;
#ifdef __cplusplus
}
#endif

我不确定这将如何与您的函数一起使用,因为您尚未将参数放入头文件中的函数原型(prototype)中。通常认为添加它们是最佳做法,因此如果仍然不起作用,请尝试。

关于c++ - 外部错误 - undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23046685/

相关文章:

c++ - 当您不取消引用时,指针不只是一个引用吗?

c++ - 不区分大小写的 std::字符串集

c++ - 为什么 std::to_string 没有短重载?为什么没有 noexcept?

c++ - 字符大小和 const void*

c++ - 在 C++ 中通过引用传递三维数组

c# - 在 C# 中引用一个对象

c++ - 使用GCC 4.8 : array used as initializer构建错误

c++ - 数据结构新手

c - 如何在 Pascal/Delphi 中调用以下 C 函数?

c - 默认 GCcflags