Visual studio #include "file.c" needed in every file - c

I recently wanted to test my C project on visual studio (I used visual studio code) but for some reason my other file (file.c) do not recognize function from my main file (main.c). I need to manually add #include in both files. I can compile the code normally using cmd (gcc main.c). If you have any idea what cause this I would be happy to hear.
main.c:
#include <stdio.h>
#include <stdlib.h>
int randNumber = 10;
#include "file.c"
int main ()
{
int a = 10;
int b = 2;
printf ("%i", multiplication (a, b));
return 0;
}
file.c:
int multiplication (int a, int b)
{
return a * b * randNumber;
}
This runs normally in vs code but not in visual studio. (I can also compile the code with cmd outside of visual studio with the command (gcc main.c)) The thing that doesn't work is the randNumber, it gets an error saying (identifier "randNumber" is undefined).

You should not include source files (.c) in other source files. software_rendering.c uses types defined in win32_platform.c. For example, the Render_Buffer structure.
You need to put the common types and definitions in a header file (.h) and include that. Keeping the Render_Buffer example: move the Render_Buffer structure definition in a header file and include that header file in both source files.
See Creating your own header file in C for details.
As a side note: please do not post images of your code, instead paste it as text and properly format it as code.

Related

Using __declspec results in "Error C2370 'In1': redefinition; different storage class"

I have a dll created using MSVC. The header file and a .def file are also present.
Here is what is exported from the dll (simple.def):
EXPORTS
simple_initialize
simple_step
simple_terminate
In1
Gain
Increment
I have a simple application that is trying to access the functions and variables inside the dll (have the .lib file as well). The MSVC project files have the necessary files provide and the application builds correctly. Here's the application code:
#include <stddef.h>
#include <stdio.h>
#include "simple.h"
#include "rtwtypes.h"
void main(void)
{
int i;
simple_initialize();
for (i = 0; i < 10; i++)
{
simple_step();
}
simple_terminate();
}
This code seems to be working fine, however, if I try to write to any of the global variables (In1, Gain or Increment) from the dll it results in a crash.
After researching I realized that the only way I can make it work is by adding
__declspec(dllimport) real_T In1;
AND
commenting out this line from the header file:
extern real_T In1;
If I do not comment this line, then I get following error:
Error C2370 'In1': redefinition; different storage class SimpleTest \SimpleTest.c 8

How to insert the content of a .h file into string for runtime compilation? [duplicate]

This question already has answers here:
"#include" a text file in a C program as a char[]
(21 answers)
C/C++, can you #include a file into a string literal? [duplicate]
(7 answers)
Closed 3 years ago.
I'm working on part of a C program where a user inputs a network filter string (think Wireshark).
A filter string like, for example
(s->field_a == 1 || s->field_c <= 10) && ! (s->field_c % 2)
Is entered by the user and pasted into a function in a temporary file, which is compiled as a shared lib and loaded wit dlopen. The function simply evaluates the string.
Now, the type of "s" struct is defined in some .h file, let's say struct.h.
Obviously struct.h won't be available for the runtime compilation. I can just paste its content to a string and fprintf it, but then I'd have to re-paste it whenever I change the header.
I could write a script that'd do it during building, but maybe there's a better option.
Is there a way to "paste" the content of the file as a string using e.g. the preprocessor?
Some code to illustrate what I'm trying to do:
struct.h:
struct example_struct
{
int field_a;
int field_b;
int field_c;
};
main.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include "struct.h"
int main(int argc, char *argv[]) {
struct example_struct s;
char filter_string[] = "(s->field_a == 1 || s->field_c <= 10) && ! (s->field_c % 2)"; // what the user can input
FILE *f = fopen("/tmp/prog.c","w");
// here I'd like to insert contents of struct.h into f
fprintf(f, "int filter(struct example_struct * s) {\n");
fprintf(f, "return (%s);}\n", filter_string);
fclose(f);
system("gcc /tmp/prog.c -o /tmp/prog.so -shared -fPIC");
// load and use function...
}
Edit:
I don't need an actual representation as a char[], it can be a string literal.
I'm trying not to use xxd or some other tool before building the program, I can do that fine by inserting the text with a python script or whatever. I'm just curious if a "pure" solution is possible.
Is there a way to "paste" the content of the file as a string using e.g. the preprocessor?
[...]
I'm trying not to use xxd or some other tool before building the program, I can do that fine by inserting the text with a python script or whatever. I'm just curious if a "pure" solution is possible.
The C language does not have a built-in feature for including compile-time file contents as character array contents, whether in string literal form or any other kind of initializer form. If you want that then you need to use some kind of code generator.
But I'd like to challenge your assumptions for a moment. You say,
Obviously struct.h won't be available for the runtime compilation.
, but I don't see why that has to be true. At least in principle, nothing prevents you from packaging the header file together with the program, installing it in a location known to the program (or that the program can discover or be configured for) and using it as a normal header.
Found a trick with defines that'll do it here.
It's a bit wacky, but it does exactly what I wanted.
In struct.h:
#ifndef STRINGIFY
#define STRINGIFY(x) x
#endif
STRINGIFY (
struct example_struct
{
int field_a;
int field_b;
int field_c;
}; )
#undef STRINGIFY
That way when it's included as a regular file, the define does nothing.
In main.c I can now insert the string as follows:
#define STRINGIFY(x) #x
const char * header_string =
#include "struct.h"
;
#undef STRINGIFY
Code from "struct.h" will be included as a string literal.
It is not a language question, but some development systems could help. For example the Windows API has the notion of resource which allows to embed a file in an executable and access that resource as run time more or less as if it were an internal file.
According to those other SO questions:
Embedding resources in executable using GCC
C/C++ with GCC: Statically add resource files to executable/library
Is there a Linux equivalent of Windows' "resource files"?
(and probably others: just follow the possible duplicate links), there are various ways with gcc on Linux from directly using the ld linker, to using external tools like ImageMagick.
But IMHO there is nothing wrong in just including the .h include file into the pack of distributable files that are required to use the application.

How to call a function from another file into main function in c?

I am using qt and created a c project. I have created two files one header file and source file. I have declare a function into header file. So that I can call it from main function. But when I compile and run, I got "undefined reference to " error. How to solve this issue ? I am using qt 5.5 ide.
My Code:
header file
chapter_1.h
#ifndef CHAPTER_1_H
#define CHAPTER_1_H
//include all header files
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* function declaration */
int sum(int x, int y);
#endif // CHAPTER_1_H
source file
//include header files
#include "chapter_1.h"
int sum(int x, int y)
{
int result = x+y;
return result;
}
main file:
#include "chapter_1.h"
int main()
{
sum(23, 23);
return 0;
}
It's not a compiler error. It's a linker error. You just need to include both source files (main.cpp and chapter1.cpp) into your project.
I solved the problem. The problem was, file created as .cpp. Now I have changed it into .c and not it worked. Thanks to all.
You must tell the qmake which are the source files that you want to use to generate program. There is a couple of variables defined in project file ( *.pro) which are responsible for this and other information. SOURCES defines the source files to use, HEADERS - you guessed, the headers.
HEADERS = chapter_1.h
SOURCES = main.cpp chapter_1.cpp

How do I manage lots of example codes from a textbook in a single project?

I am studying C with a textbook, and it has of course a lot of example source code for me to practice.
I had no problem with managing these code files when I was just studying with gcc, a text editor and terminal.
And now I wanted to use an IDE so I can get hints before compiling each source code, so downloaded one and trying to put every code file into a single project template the IDE offers.
The code files are usually short, and always have main function for each, so creating a project and importing all of them prevented me from compiling: I have multiple main function which I should have not.
Here is an example so I can describe what the problem I have:
I now started 7th chapter in the book, so I created a project named 'ch7'. And I have currently two example codes. The project can't be compiled with all the codes at once, so I commented every main function in each of the examples and made a new main.c, containing the main function part from the examples.
example code 1 (find.c) - has 6 functions, including 1 main function (I made it so it's now in comment block)
#include <stdio.h>
#include <string.h>
int NUM_ADS = 7;
char *ADS[] = { ... };
int sports_no_bieber(char* s) { ... }
int sports_or_workout(char* s) { ... }
int ns_theater(char* s) { ... }
int arts_theater_or_dining(char* s) { ... }
void find(int (match)(char*) ) { ... }
/* int main() { ... } */
example code 2 (test_drive.c) - has 7 functions and 1 structure, including 1 main function.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare_scores(const void* score_a, const void* score_b) { ... }
int compare_scores_desc(const void* score_a, const void* score_b) { ... }
typedef struct { ... } rectangle;
int compare_areas(const void* rect_a, const void* rect_b) { ... }
int compare_names(const void* name_a, const void* name_b) { ... }
int compare_areas_desc(const void* rect_a, const void* rect_b) { ... }
int compare_names_desc(const void* name_a, const void* name_b) { ... }
/* int main() { ... } */
I commented the main function for each codes because I wanted to use them in a new main.c:
#include <stdio.h>
#include <stdlib.h>
#include "find.c"
#include "test_drive.c"
// this list will grow as I make more example codes and include them like this.
// And yes, I know this part brings problem. I shouldn't directly include code files like this.
int main(int argc, char** argv) {
/*
statements for main function in example code 1;
*/
statements for main function in example code 2;
// this part is uncommented, because I am testing this one.
/*
statements for other example codes will be here after...
*/
return(EXIT_SUCCESS);
}
This of course returned compile errors: multiple definition of the functions.
I know I can make a header and put function declarations for every function existing in all the example codes, and then include that header to my new main.c.
But is this the only way to manage all example codes in a single project in an IDE? The files I've shown here is only two, but a header for them should have 11 function declarations. And I have lot more example codes, from chapter 1 to 6, including about 30 c files (and much more total amount of functions in each c file of course), some h, csv and txt files for specific example source codes.
If I have to make a header for all of them, it wouldn't be only consuming lots of time but also will force me to add another few lines to the header every time I write a new code as I keep studying.
It seems much ineffective compared with just writing a code file in a text editor, opening terminal and calling gcc to compile it.
So I think there should be much effective way to manage such example code files in a single place, which shouldn't only be a 'project'. I want to find a way in which I can get advantages of using IDE while code file management doesn't go too complicated.
Remove Main from all the files.
Create another files for Main.
Segregate all the files and implement everything in a procedure/function as you wanted.
In your Main file include only those file which you need and do the operation as you wanted.
As you go further in chapter try to keep the logic in particular procedure/ function such that you can again reuse it in the Main file.
Since it is really high level, i am assuming you are going through the chapters and trying the examples.

Header Files in C

I have been reading about C for a while now and decided lets write a little add program, nothing fancy at all. My understanding of C headers is that they are "interfaces" (such as like java and other languages) but where you can also define variable that either have set values or not..
So I wrote this:
#include <stdio.h>
#include <stdlib.h>
#include "sample.h"
int main(int argc, char** argv) {
printf("hello World\n");
add(12, 18);
return (EXIT_SUCCESS);
}
int add(int a, int b){
int value = a+b;
printf("value = %d\n", value);
return 0;
}
It has a header file that looks like such:
#ifndef SAMPLE_H_GUARD
#define SAMPLE_H_GUARD
int add(int a, int b);
#endif
I thought header files, and this is where I am lost on their definition, was suppose to define the use of add, so all I would have to do is call add - From my understanding, I define the rules of add and then implement the functionality of add....
Also, A lot of the material I have read shows one header file for multiple C files. where as a lot of projects today have one header per one c, meaning Sample.h belongs to Sample.c and nothing else.
Can some one shed some light on this?
Could I have done this like so:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "sample.h"
int main(int argc, char** argv) {
printf("hello World\n");
add(12, 18);
return (EXIT_SUCCESS);
}
add.c
#include <stdio.h>
#include <stdlib.h>
#include "sample.h"
int add(int a, int b){
int value = a+b;
printf("value = %d\n", value);
return 0;
}
sample.h
#ifndef SAMPLE_H_GUARD
#define SAMPLE_H_GUARD
int add(int a, int b);
#endif
I believe in the book I was reading: C Programming Language they had a calculator example split up like this, my question is how does C know where add is defined? It knows the rules for it based on the header file, i think, but not where the actual implementation is ....
There example where they split of the files like such doe not have something like #include "add.c" all they do is include the header file in the files that either implement or use this functionality.
Note: obviously the calculator example and my example are going to be different but fundamentally the same - for those who have the book. I am just lost on how to use header files effectively and efficiently.
A header file in C would declare the function add for those modules that need it, but not define the function. The function is still to be defined in its own module (e.g., in your case, add.c).
So in general, to make a function foo available to several modules, you would normally:
Choose a header file (maybe it's own if there are other associated
defines, etc) to declare foo. For example, perhaps foo.h would
have void foo(...);
In some module, perhaps foo.c, you would define the complete
function foo.
In any module that wants to call foo, you would #include "foo.h"
(or whatever header you used) and call the function.
When you compile/link the code, you would make sure all modules,
including foo.o or whatever module has foo defined in it, were
present.
A declaration, given in the header file, provides (of course) the function name, the function return type as well as listing all the parameters and their types. This is all the compiler needs to know to figure out how to call the function from the calling module. At link time, addresses are all resolved so that the modules then know exactly where the function is in its own particular module.
My understanding of C headers is that they are "interfaces" (such as
like java and other languages) but where you can also define variable
that either have set values or not..
This is not correct. You cannot "define" variables - well, you can but that will cause multiple definitions error while compiling code if you include header more than once.
Could I have done this like so:
Regarding your code - both variants are correct. C language uses headers to read declarations and hence headers are optional as well. You can have your code split into as many as you want .h and .c files. Compiler will create an object file for each .c file. All .h files included in a c file are basically embedded in that C file "before compilation" i.e. in preprocessing phase. Linker then comes in picture which combines objects to produce the executable.
Please don't hesitate if something is not clear in my answer.

Resources