Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Often during programming contests I forget which library contains which function. Hence I require some C code which can print the available functions with a specific library. eg. usage:
showAvailFunctions("stdlib.h")
and it would print all the available functions with stdlib.h library
Create a C program file with the include directive for the include file you want to see.
For instance:
#include <stdlib.h>
Compile with Preprocessor output to generate a file, usually a file with an extension of .i and you will have the complete contents of the include file.
For Visual Studio, you may need to indicate whether you want to keep the comments or not.
The output file should appear in your working directory.
A more involved example of an approach is as follows. This is a C source text file which does a series of includes with special markers to show what is where.
The program at the bottom of the source file is a simple filter program which reads the C Preprocessor file generated and removes most of the clutter such as blank lines or those "#line " lines of output which specify a line number and the file it came from.
You will need to add whatever include files you want to see. Then compile it twice, once with C Preprocessor output enabled to generate a file containing the C Preprocessor output and once with C Preprocessor output disabled to generate an actual executable file. Your C compiler may provide options to do both steps in a single compile. I could not see how to do that with Visual Studio 2013.
Here is an example source file. I expect you may need to tailor this for your compiler and development environment. This compiles and generates output with Visual Studio 2013. I created a simple .bat file which runs this application from the command line and redirect STDOUT to a text file that contains the filtered C Preprocessor output.
#define MAKE_SEP_STRING "<!-- #$%^&*()_+-=qwrtv -->"
#define MAKE_SEP_STRING_END "<!--END #$%^&*()_+-=qwrtv -->"
#define MAKE_SEP_BEGIN(x) static const char X_##x [] = MAKE_SEP_STRING #x;
#define MAKE_SEP_END
MAKE_SEP_BEGIN(stdio);
#include <stdio.h>
MAKE_SEP_BEGIN(stdlib);
#include <stdlib.h>
MAKE_SEP_END
#include <string.h>
int main(int argc, char* argv[])
{
if (argc < 2) {
printf("output file must be specified.\n");
return 1;
}
else {
char *sep = MAKE_SEP_STRING_END; // if we want to determine where each file begins or ends.
FILE *pFile;
fopen_s(&pFile, argv[1], "r");
if (pFile) {
char hugeBuffer[4096];
// read through the C Preprocessor output file and eliminate empty lines.
// there can be a lot of empty lines.
while (fgets(hugeBuffer, 4000, pFile)) {
if (strlen(hugeBuffer) > 5) {
// discard all those tons of #line n text lines generated by the Preprocessor
if (strncmp(hugeBuffer, "#line ", 6) == 0) continue;
if (strcmp(hugeBuffer, sep) == 0)
{
break;
}
printf("%s\n", hugeBuffer);
}
}
fclose(pFile);
}
}
return 0;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Let's say I am creating a program and a makefile, and I want to be able to create three different executables with different names that all do different things, all with the same source file. Is this at all possible?
Option 1
Write a program that examines argv[0] to see what name it has been executed with and branches based on that:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
size_t length = strlen(argv[0]);
if (3 <= length && strcmp(argv[0]+length-3, "foo") == 0)
printf("This is the foo program. It does foo things.\n");
else if (3 <= length && strcmp(argv[0]+length-3, "bar") == 0)
printf("This is the bar program. It does bar things.\n");
else
printf("This is the default program. It does default things.\n");
}
Compile the program and call the executable x or some other name.
Presuming you are using some version of Unix, link the file to more names:
ln x foo
ln x bar
Run the program with various names:
% ./x
This is the default program. It does default things.
% ./foo
This is the foo program. It does foo things.
% ./bar
This is the bar program. It does bar things.
Option 2
Use preprocessor symbols to build different programs. The source code can be:
#if Option == 1
#include "Program1.c"
#elif Option == 2
#include "Program2.c"
#else
#include "ProgramDefault.c"
#endif
The source code does not have to be in separate files. The above is only an example, and all of the source code could be in the file directly instead of included with #include.
With GCC and Clang, you can define a preprocessor symbol with -DOption=value on the command line to compile the program. The rules in a makefile can build the different programs by using different values in the compile command.
I'm currently doing an exercise where I have to create a program that takes all the code that is written inside it, and outputs it to the screen when the program is executed.
The exercise suggests that we may find it appropriate to change the file names of the program in the future - and assuming that the renaming is done in a coordinated manner, i.e. the source file and the execution file are given the same new name (except for the extension), the program should work correctly, without the need for any changes to the source code, and without the need to recompile.
The C program itself is called 'prnt.c'-
I wrote the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ENDFILEC ".c" /* extension */
int main(int argc, char *argv[])
{
FILE *filePointer;
int character;
char *fileNameToOpen;
fileNameToOpen = (char *)malloc(strlen(argv[0]) + 3); /* allocating memory for string + 3 for the extension - '.c' and \0 */
strcpy(fileNameToOpen, argv[0]);
strcat(fileNameToOpen , ENDFILEC); /* ending '.c' in the end */
filePointer = fopen(fileNameToOpen, "r");
while(!feof(filePointer))
{
character = fgetc(filePointer);
printf("%c" , character);
}
fclose(filePointer);
return 0;
}
I made a 'makefile' to compile the program and I made it so that the executable would be called 'prnt1'.
basically, like the following:
prnt1 : prnt.c
gcc -ansi -Wall -pedantic prnt.c -o prnt1
The compilation worked, but whenever I run the program itself, it gives me a runtime error, saying: "Segmentation fault (core dumped)". When I look at the code itself, I don't seem to reach a memory that doesn't belong to me, so what could be an explanation for that problem and what can be done about it? Thank you in advance for your help.
Since you said that the executable is named "prnt1" and the source file (which you want to read the code from) is named "prnt", argv[0] has the name of the executable (i.e. "prnt1") and, when ".c" is appended to argv[0], it becomes "prnt1.c" – which is definitely not the file you are trying to read from; athen, since this file doesn't exist, you're getting a segmentation fault.
So, as Tom Karzes said, always check the return value of fopen().
This question already has answers here:
C/C++ line number
(10 answers)
Closed 6 years ago.
Is there any way to get the source code line number in C code in run time?
The thought behind it is, suppose a software is made in plain C language. the .exe file is distributed to a user who knows nothing about C. Now if there is any error, the user can see the line number and report the error to the manufacturer so that the debugging can be done at manufacturer site. I just to debug the run time errors and get the corresponding line numbers in the source code while running it. I am a beginner in these stuffs.
If you are using the GCC compiler, you can use the Standard Predefined Macro - __LINE__ as a line number placeholder.
The compiler will fill in the line number while compiling.
Eg :-
printf("%d",__LINE__);
Use gdb instead. But I guess it will work:
if(someThingsWrong())
printf("wrong at line number %d in file %s\n", __LINE__, __FILE__);
You can use the built-in macros __LINE__ and __FILE__, which always expand to the current file name and line number.
#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;
}
#include "JoystickDriver.c";
#include "joystick.c";
task main()
{
while(true)
{
getJoystickSettings(joystick);
if(joy1Btn(8) == 1)
{
motor[motorC] = 100;
}
else if(joy1Btn(7) == 1)
{
motor[motorC] = -100;
}
}
}
This is to make a motor spin to intake balls into our robot.
The errors I got were:
File "C:\Users\Kunal Patel\Desktop\SourceFile002.c" compiled on Oct 12 2014 13:37:47
**Severe*:Couldn't open '#include' file 'joystick.c'
You should not be using a semi-colon after the file name:
#include "JoystickDriver.c"
#include "joystick.c"
It is aconventional to include .c files in another; there can be good reasons for doing so, but they are few and far between, on the whole.
Were you actually looking for the .h files?
#include "JoystickDriver.h"
#include "joystick.h"
Whether it is C source or a header, you may need to specify a command line option so that the compiler knows where to look for the code. The compiler will normally look in the directory holding the source code being compiled and in a bunch of system-defined places. You may need to tell it to look somewhere else to. On Unix, that would be with -I /some/where/else; the notation will be equivalent on Windows, but likely not identical.
Your declaration of main() suggests you are in an embedded environment. If these comments don't help, you may need to cite your environment more carefully.
I'd like to use C program to find the total number of directives like #include, #define, #ifdef, #typedef, etc. Could you suggest any logic for that? I'm not interested in using any scripting or tools. I want it to be done purely using C program.
Store all the directives in an array of pointers (or arrays).
Read the C file line by line and check if the first word starts with any of the directives in the list excluding any whitespaces at the beginning.
char *directives[]={"#assert", "#define#, ......};
int count[NUM_DIRS]= { 0 };
Everytime you find a match increment the correspondin index of the count array. You can also maintain another counter for total to avoid adding values in count array.
Assuming you don't want to parse them, or any other kind of syntactic/semantic analysis, you can simply count the number of lines which start with 0 or more whitespace characters and then a # character (losely tested, should work fine):
#include <stdio.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
FILE *f = fopen(argv[1], "r");
char line[1024];
unsigned ncppdirs = 0;
while (feof(f) == 0) {
fgets(line, sizeof(line), f);
char *p = line;
while (isspace(*p))
p++;
if (*p == '#') ncppdirs++;
}
printf("%u preprocessor directives found\n", ncppdirs);
return 0;
}
You might take advantage that gcc -H is showing you every included file, then you might popen that command, and (simply) parse its output.
You could also parse the preprocessed output, given by gcc -C -E ; it contains line information -as lines starting with #
Counting just lexically the occurrences of #include is not enough, because it does happen (quite often, actually, see what does <features.h>) that some included files do tricks like
#if SOME_SYMBOL > 2
#include "some-internal-header.h"
#define SOME_OTHER_SYMBOL (SOME_SYMBOL+1)
#endif
and some later include would have #if SOME_OTHER_SYMBOL > 4
And the compilation command might BTW define SOME_SYMBOL with e.g. gcc -DSOME_SYMBOL=3 (and such tricks happen a lot, often in Makefile-s, and just optimizing with -O2 makes __OPTIMIZE__ a preprocessor defined symbol).
If you want some more deep information about source programs, consider making GCC plugins or extensions, e.g. with MELT (a domain specific language to extend GCC). For instance, counting Gimple instructions in the intermediate representation is more sensible than counting lines of code.
Also, some macros might do some typedef; some programs may have
#define MYSTRUCTYPE(Name) typedef struct Name##_st Name##_t;
and later use e.g. MYSTRUCTYPE(point); what does that mean about counting typedef-s?