I'm an experienced MATLAB user but totally new to C and MEX files. I have a complex program written in C that I need to call from within MATLAB. The program consists of a few dozen files in a folder, including one called main.c that processes inputs from the command line passes the results to other classes that do the actual calculations.
Normally, to install this program from the command line, I would run ./configure, make at the UNIX command prompt. Then, to run the program, ./runMyProgram -f input_file.txt -p some_parameters. The program takes a text file consisting of a list of numbers as input and prints a table of results in the command window. I want to feed the program a MATLAB array (instead of a .txt file) and get back an array (instead of a printed table of results).
I have read the MEX documentation from The Mathworks (which I found rather opaque), as well as some other "tutorials", but I am totally lost - the examples are for very simple, single-file C programs and don't really discuss how to handle a larger and more complicated program. Is it enough to replace the main.c file with a MEX file that does the same things? Also, how do I compile the whole package within MATLAB?
I would be grateful for any plain-English advice on where to start with this, or pointers to any tutorials that deal with the subject in a comprehensible way.
Yes. Normally replacing a main.c file with MEX file is the process. In your case since you already have complex build setup, it might be easier to build a library and then build a separate mex file which just links against this library. This will be much easier than building the whole thing using mex command. If you export the function you need to call from your library, you can call it from your mexFunction. mexFunction can do all the creation and reading of mxArrays. A simple sample mexFunction can be,
#include "mex.h"
// Include headers for your library
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
void* x = mxGetData(prhs[0]); // Assume one input. Check nrhs
plhs[0] = mxCreateDoubleMatrix(10,10,mxREAL); // Create 10x10 double matrix for output
void* y = mxGetData(plhs[0]);
yourLibraryFunction(x, y); // Read from x and write to y. Pass sizes in if needed
}
Related
I'm using a book, and now I'm studying external variables. I'm supposed to use a function located in another file and return a value from that function. But I don't understand how does this happens exactly. This is the code provided by the book:
This is the code in the first file:
#include <stdio.h>
double getCircum(double);
double PI = 3.14;
int gi;
int main(void)
{
double r = 5.87;
const double PI = 3.14;
printf("%.f", getCircum(r));
}
This is the code in the other file:
external double PI;
double getCircum(double r)
{
return 2 * r * PI;
}
The output is supposed to be 36.88. but I keep getting an error message that the file is not the directory. I don't know what file it that. Also, I don't really get how the code is supposed to look for a function in a different file, is the code missing something?
This is possible through to the linking process.
When reading your C first file, the compiler will output an object file which contain unresolved references to symbols like printf, getCircum because they are declared (printf in <stdio.h> and getCircum in your first file) but not implemented (you didn't wrote them code in the first file).
When reading the second file, the compiler will miss the definition of PI.
This doesn't prevent him from producing valid object files. After removing the line double PI = 3.14 (it miss a ;), compile without linking with :
cc -c -o 1st_file.o 1st_file.c
cc -c -o 2nd_file.o 2nd_file.c
This will output two object files, if you run obj-dump -t 1st_file.o 2st_file.o you will see a list of provided and unresolved symbols of both files.
Now we will link with cc -o program.exe 1st_file.o 2nd_file.o. The C compiler will link both objects and some system-wide ones inside program.exe.
And voilĂ !
In your case cc -o program.exe 1st_file.c 2nd_file.c will do the job. But in real program, recompiling the whole program at each test take a lot of time, I have a private project which take 3,5 seconds to link vs 17,5 to recompile everything for 4k lines of code, Linux itself has more than a 2M lines of code...
Finally, post the console output and build command in the question, my answer make the important assumption that you are on a Linux with a working C compiler and GNU binutils, StackOverflow has a great doc here https://stackoverflow.com/help/how-to-ask to ask good question which have more chances to be solved
Edit: Defining PI 2 times here is not an error
I have several files in the structure
/algorithms
/a1
a1.c
/a2
a2.c
/a3
a3.c
Each of these files contains a function of the same name. Each has the same signature, except for the name (which is the same as the filename). Essentially, each algorithm is a different implementation of the same thing -- different means to the same end. There may however be small helper functions.
The content of the files (comments, functions, layout, etc) cannot change.
I want to create some method that will test each algorithm. This method is not confined to being implemented in C.
I have a C file that essentially contains three functions:
// Runs the algorithm, which modifies the given integer array.
void run(void (*algorithm) (int*, size_t));
// Checks that the algorithm successfully completed and
// the array is correct.
int check(int*, size_t);
// Should call run() with appropriate algorithm and a random data set
// and then call check() to make sure it worked.
int main(int, char**);
I need an automated way of including the appropriate files and then calling
the function within them. Currently, I have a bash file that gets all the algorithms, copies the tester file, prepends an #include statement at the beginning and a generated injected_main() function that gets called by the actual main() function. It runs the copied tester and then deletes it.
function testC() {
local tempout=temptest.c
local filename="$(basename -- $1)"
local functionname="${filename%.*}"
local main="void injectedMain() {test(&$functionname);}"
local include="#include\"$1\"\n$main"
touch $tempout
chmod +x $tempout
printf "$filename: "
cp $TESTER_C $tempout
printf "$include" >> $tempout
gcc $tempout -o tempout -Wall -Wextra -pedantic
./tempout
rm $tempout tempout
}
Where the function is run in a loop for every algorithm C file.
However, this method is prone to error, not extendable, and just downright ugly. Is there a better way to do this?
Combine your existing code and #Herve's answer.
You could let the bash script just collect all algorithms and build a C source like that proposed by #Herve. This way there will be no error prone manual step.
To run all tests compile this automatically generated source and link it to your test runner. Let the latter loop through all.
Can't you just a header including your algorithm implementations and loop through all of them?
Something like
#include "a1/a1.h"
#include "a2/a2.h"
#include "a3/a3.h"
typedef void (*AlgorithmImplemetation)(void); //Your algorithm function signature goes here
AlgorithmImplemetation *all = {
a1,
a2,
a3
};
Then include this header in your main.c and loop through all.
I'm new to programming and currently I'm learning C programming. I'm writing codes on the code blocks and in it using GCC compiler. When I create a new project, (as you know it creates main.c file with it) and due to that I'm not able to compile another file in that project.
File 1:
#include<stdio.h>
int main()
{
int a,b,c,d;
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
d=a;
if(b>d)
d=b;
if(c>d)
d=c;
printf("\n The maximum of three numbers is %d",d);
}
File 2: main.c
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}
When I compile the first programme, it shows the following error:
multiple definition of 'main'
first defined here
I've searched every where I could and I'm not able to solve this. In one of the answers here on stack overflow, someone had suggested to write this in
(Project->Build options...->Linker settings (tab))
-Wl,--allow-multiple-definition
When I wrote it, there were no errors. But it wasn't able to run my File 1 and instead, it runs that main.c file. Even when I close the main.c file, it opens there again and runs main.c file which gives the output "Hello World!".
Initially when I was using code blocks there were no such errors. I don't know why this is happening and I've not much knowledge about compilers.
As noted in comments you can only have one main function.
So when you start a new project you need to replace the main.c file with the main.c file you want to use. Or you can edit the 'hello world' main.c program.
When you start a new project in code::blocks you can get a new directory with a simple program that prints 'Hello World'. This file is usually main.c. You need to edit this file or replace it. The reason that code::blocks puts this simple main.c program in the new project is so that you can compile it and test your system without having to write a new program.
Some computer languages allow you to use the same function name for different functions ( which are identified by their parameters and sometimes return types ). That's called overloading. C does not allow this. Functions in C must have unique names.
The main() function is a special one in C as it is used as the standard entry point for applications. That is, the main() function will be called first and your application should start and (typically) end in that function.
As a beginner I would suggest you avoid automated editor features that create and build projects for you. You will miss out on learning how things work doing that. Use an editor to start from empty files and learn how they all connect and how to use the compiler from the command line. The command line is something every beginner should start from, IMO.
It may be harder to learn, but it will give you a much better feel for what is going on.
I guess what you maybe trying to do is have multiple sandbox "gists" that you may wanna run all as their own main function. If that is the case, then just close your project and open the files directly. As long as they are not in a project, they will run fine.
I have a C program which calculates f(x) for some x values (main.c). I need to get a line of c code from file and that code is my function to execute (function.dot). For example function.dot will contain:
pow((1-x), 0.333);
I need to read this file, get that function and execute in my code (main.c). How can I do that?
Basic steps would be:
Read the line from the file.
Generate a new source file which wraps the line of code inside appropriate code.
Invoke a compiler to compile that code into a shared object/dll.
Load the library.
Call the function in the library.
If the single line of code in the file could be any language, it would be far easier to use something like Lua that can be linked into your main executable.
I will provide some options:
Switch to another interpreted language including python, ruby, perl, ...
If you are working on small project, I recommend this option.
Implement your own interpreter in C.
Parse your input, analyze it, execute it. You might find open source implementations: one choice is slang
http://www.jedsoft.org/slang/doc/html/slang.html
Call C compiler and dynamically link it.
It depends on your operating system but system or exec functions help you to call your compiler to handle your input file. If you are using Linux, dlsym can open a shared-object compiled from your input file.
You might need to convert your input file into C program.
Very slow to compile but fastest to run.
You have several options I can think of:
1) Switch to any number of interpreted langauges (python, perl, etc.) which support this as an easy mechanism. (Example: in python
data = open("function.dot").read()
x = 5
eval(data) #note that this is unsafe if you can't trust data, and you might also need to play with environment
)
2) You could wrap the code in it's own c file... something like (but with more error checking etc... you probably don't want to do this)
void generate_c_program(char *line)
{
FILE *fp = fopen("myfile.c","wt");
fprintf(fp,"#include <math.h>\nint main(char *argv, int argc) {\n double x = atof(argv[1]); printf(\"%f\",(%s));}\n");",line); //this is also unsafe if you can't trust data
fclose(fp);
//now execute gcc myfile.c
//now execute a.out
//optionally cleanup by deleting a.out and myfile.c
}
3) Effectively write your own compiler / parser (which may be fairly easy IF you've done this before and the number of functions / operations you need to support is small or may be a much bigger deal and will rather not fit in this answer)... the extensible way would be to use LEX/YACC or similar)
I wrote this in notepad and then compiled it with lcc-win, using the command lc hello.c
#include <stdio.h>
int main(void)
{
printf("Hello World\n");
return 0;
}
The resulting exe was 100 KB. Seems kind of huge for a program that just prints Hello World. Is this normal? Can I reduce the size? 100 KB isn't really an issue these days but it still seems kind of big for what it does. Wouldn't be too bad if every C code I write comes out as a 100 KB exe though.
1- Everytime you use the include <> tag you do make a link with a c library and load it in your programm.
That is also why it is important to include only in the files that actualy need the library functions.
2- On the other part, the binary that you generate is always full of important informations (cf : libelf or ASM), headers, steps that needs to be here if you want to programm to be run nicely. This does take space to.
This is a really simple question, what happens to the lcc-win is the same with the C Compiler Digital Mars, he do not link the exe with dlls containing the functions printf and etc., functions are linked together with EXE, so no requerindo that your computer has the DLLs.
Look, I created a simple Hello World EXE, and I opened hin in Hex Editor.... the printf function is stored in msvcrt.dll, and, the exe don't have this dll in import section...
And, u can found the source definition in this other picture:
Use this style of function definition is more fast then make a dll call....