gpt4 book ai didi

C++ 未定义对代码中实现和模板化的函数的引用

转载 作者:行者123 更新时间:2023-11-28 07:23:11 25 4
gpt4 key购买 nike

首先,我要调用的函数不在外部库中。它是以下内容的一部分(我正在回到 C++,所以我想我应该从编写我自己的 cron 守护进程实现开始)

这是我的代码:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <time.h>

using namespace std;

//Global Variables:
//local time in the form of a tm struct
struct tm sysclocktime;
/*
* tm_sec int seconds after the minute 0-60*
* tm_min int minutes after the hour 0-59
* tm_hour int hours since midnight 0-23
* tm_mday int day of the month 1-31
* tm_mon int months since January 0-11
* tm_year int years since 1900
* tm_wday int days since Sunday 0-6
* tm_yday int days since January 1 0-365
* tm_isdst int Daylight Saving Time flag 0-?
*/



//Function Declarations:
bool fexists(const char *filename);
char* timetostring(struct tm timeobj);

//Functions:
int main(int argc, char* argv[]){
//error counter
int errors = 0;

//Set the current time by the system's clock
time_t now = time(0);
sysclocktime = *localtime(&now);
//Print the current time to cout:
cout << "Current time is: " << timetostring(sysclocktime) << endl;

//See if mcron.cfg (mcron config file) exists
if(fexists("mcron.cfg")){
//if mcron.cfg exists, read data from it
cout << "mcron.cfg existiert bereits!" << endl;
}else{
//if mcron.cfg doesn't exist, create it
cout << "mcron.cfg existiert nicht! :(" << endl;
}
return errors;
}


/*
* Function which tells whether a file exists
*/
bool fexists(const char *filename){
ifstream ifile(filename);
return ifile;
}

/*
* Converts the pointer to a time struct into dates and times in a string
* format like so: YYYY-MM-DD-HH-MM-SS
* For example: 2013-07-15-16-14-36
*/
char* timetostring(struct tm* timeobj){
//Declare local variable charstring which will be used to create the string of characters
char* charstring = new char[20];
//Initialize charstring with relevant time data
sprintf(charstring,"%4d-%2d-%2d-%2d-%2d-%2d",(timeobj->tm_year+1900), (timeobj->tm_mon+1),timeobj->tm_mday,timeobj->tm_hour,timeobj->tm_min,timeobj->tm_sec);
//Print the string of characters to the command line:
cout << "timetostring(): " << charstring;
return charstring;
}

这是我尝试编译它时得到的结果:

[user@computer ~/code/mcron]$ g++ mcron.cpp -o mcron
/tmp/cc9M4We8.o: In function `main':
mcron-nostring.cpp:(.text+0xd1): undefined reference to `timetostring(tm)'
collect2: Error: ld returned 1 as it's exit status

我做错了什么?

最佳答案

您的声明缺少指针:

char* timetostring(struct tm* timeobj);
// ^ here

(加上你需要调整调用)

关于C++ 未定义对代码中实现和模板化的函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19144679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com