Reputation:
I have written down a program in c and I am trying to create a log file of it.
The problem I am facing is that while printing the outputs of each line in the file I want to write some distinctive feature such as the time of execution of that line or even the line number in the code.
Is there any way I can get to know any of these two.
I don't mind if you suggest some other way to get a distinctive feature. All I want is that looking at the log file the user gets to know that a certain part of the code was getting executed.
Thanks
I am working on linux and thus using the GCC compiler....
I have made a header file and in it I am for testing purposes writing __LINE__
. What I want to do is that in a program when I include this function of header file the line number gets printed where the function is. But instead i get the line number of the header file printf statement.
What do I need to do to get the line number of the file . This is just a test format given below :-
new.h
void print()
{
printf("Line number is %d",__LINE__);
}
actual file
#include "new.h"
int main()
{
print();
}
Then I want that the line number that should be printed is that of actual file and not new.h which happens now....
Upvotes: 0
Views: 1433
Reputation: 89142
Use __FILE__
and __LINE__
to get the current file and line number.
Edit: based on your edited question. Here's a simple way to do it to start.
new.h
#define PRINT() print(__LINE__)
void print(int line)
{
printf("Line number is %d",line);
}
actual file
#include "new.h"
int main()
{
PRINT();
}
Upvotes: 0
Reputation: 4871
The line number can be obtained by the preprocessor macro __LINE__
. The file is __FILE__
. As for time, use the relevant OS library.
Or, use a logging library that support these.
Upvotes: 0
Reputation: 1905
In GCC you can get line number as "__LINE__". Filename - "__FILE__".
If you want calculate execution time then just remember time on start, get time on end and substract them.
Upvotes: 0
Reputation: 224844
Most C compilers provide some macros to identify each line, function, etc. With GCC, for example, you can use __LINE__
, __FUNCTION__
, and so on. Check your compiler documentation for details. To get a timestamp, you'll need to let us know what system you're working on.
Upvotes: 2
Reputation: 101473
If you want the actual date and time the function was executed, try asctime()
. There is a good reference on how it's done here.
This will output something akin to Sat May 20 17:36:17 2000
. If you want the time in seconds since the program started, have a variable such as int startTime = time()
which holds the program start time in seconds from the Unix Epoch. Then, simply print startTime - time()
to get the number of seconds since program start.
Upvotes: 2