有没有办法在运行时获取C代码中的源代码行号? 它背后的想法是,假设一个软件是用纯C语言编写的。 .exe文件分发给对C一无所知的用户。现在,如果有任何错误,用户可以看到行号并将错误报告给制造商,以便可以在制造商现场完成调试。我只是调试运行时错误并在运行时获取源代码中的相应行号。我是这些东西的初学者。
答案 0 :(得分:3)
如果您使用的是GCC编译器,则可以使用标准预定义宏 - printf("%d",__LINE__);
作为行号占位符。
编译器将在编译时填写行号。
例如: -
#include <stdio.h>
#include <math.h>
int main (void)
{
double cost;
int loonies, quarters, dimes, nickels, pennies;
float loonreq;
float balance;
printf ("Please enter the amount to be paid: ");
scanf ("%lf", &cost);
printf ("Change Due: $ %.2f\n", cost);
loonies = cost;
printf ("Loonies required: %d, ", loonies);
loonreq = cost - loonies;
printf ("balance owing: $ %.2f\n", loonreq);
quarters = (int)(((int)(100*loonreq))/25);
printf("num quarters: %d \n",quarters);
balance = loonreq - (quarters*.25);
printf("balance owing: %.2f$ \n", balance);
dimes = (int)(((int)(100*balance))/10);
balance = balance - (dimes*.1);
printf("num dimes: %d \n", dimes);
printf("balance owing: %.2f$ \n", balance);
nickels = (int)(((int)(100*balance))/5);
printf("num nickels: %d \n", nickels);
balance = balance - (nickels*.05);
pennies = (int)(balance*100);
printf("balance owing: %.2f$ \n", balance);
printf("num pennies: %d \n", pennies);
return 0;
}
答案 1 :(得分:2)
您可以使用内置宏__LINE__
和__FILE__
,它们会一直扩展为当前文件名和行号。
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc<2)
{
printf("Error: invalid arguments (%s:%d)\n", __FILE__, __LINE__);
return 0;
}
printf("You said: %s\n", argv[1]);
return 0;
}
答案 2 :(得分:2)
改用gdb。但我想它会起作用:
if(someThingsWrong())
printf("wrong at line number %d in file %s\n", __LINE__, __FILE__);