Large C code not compiling with MATLAB's mex - c

My overall goal is to use a C model inside my MATLAB code. The C model is large (over a dozen .c files, which are all run from cModel.c) and can be successfully compiled then run in the terminal by
make cModel
cModel.x startingfile.inp
as the C model is correctly built for normal C compilers.
However, MATLAB's mex function is not compiling this C code. I'm a total novice with mex and I am pulling my hair out trying to understand what the problem is.
I think (and reading some similar problems on stackoverflow backs this up) that the problem is around creating a mexFunction. My attempt currently is
/*function AA_mexWrapper.c*/
/*Include the MATLAB mex header*/
#include "mex.h"
/* The gateway function */
void mexFunction( )
{
/* Main() of the C Model*/
cModel(); /* cModel writes files. We don't care about the nonexistant returned variables*/
}
This generates the error (using mex AA_mexWrapper cModel) :
Error using mex
/Users/Filepath/ cModel.c:215:5: warning:
implicit declaration of function 'main' is invalid in C99 [-Wimplicit- function-declaration]
main(int argc, char **argv);
^
/Users/Filepath/ cModel.c:215:10: error:
expected expression
main(int argc, char **argv);
^
1 warning and 1 error generated.
What is MATLAB doing and how do I fix it? I really just need it to treat cModel.c like a normal C compiler would.
PS. I have no idea what (int argc, char **argv) are in the C code. They are totally undefined, presumably they come from the optional user input of a filename containing non-default parameters for the model.
PPS. I will need to run the C model inside matlab by pointing it to a text file containing various model options. I hope that MATLAB can deal with this, but I'm starting to have my doubts...

You cannot call an executable like a function; the name of the executable is not "exported" the way you might think.
How about a simple solution? build your executable outside MATLAB and ask MATLAB to just run it; here's a piece of code that would do that (assuming that the cModel.x is in the same folder as the script/function that calls it):
system('./cModel.x startingfile.inp');

Related

How do I properly define and use a function whose return type is a user defined structure? (In C)

I did my best to search for help on this but given the keywords for this problem, I kept getting basic tutorials that didn't have my specific problem.
I was given a C library to use that defined "Matrix" as a structure:
typedef struct
{
int height, width;
double **map;
} Matrix;
I am writing a function that needs to output a matrix. My code currently looks like:
Matrix convolve(Matrix data, Matrix filter) //this is line 28 btw
{
Matrix out;
<code>
return out
}
So far everything compiles. Then I try to use it in my main() block:
int main()
{
double a1[4][5] = <a ton of numbers>
double f[3][3] = <a ton of other numbers>
Matrix m1 = createMatrixFromArray(&a1[0][0],4,5); //from given C library
Matrix mf = createMatrixFromArray(&f[0][0],3,3);
//This is the line that doesn't compile, which is line 14:
Matrix m2 = convolve(m1, mf);
}
Then Developer Command Prompt for VS 2017 says:
(14) error C2440: 'initializing': cannot convert from 'int' to Matrix'
(28) error C2371: 'convolve': redefinition; different basic types
What am I doing wrong? Thank you in advance for your help.
It's difficult to be sure because you didn't post your complete code, but the combination of these two error messages strongly suggests that the compiler saw a use of the convolve function before it was declared. For historical reasons, when a compiler sees a function that it doesn't know about, it assumes that this function returns int, rather than complaining and aborting the compilation. From the code you show, that first use would be line 14. Since the returned int is assigned to a Matrix, the compiler tried to convert the value, but there's no conversion between int and Matrix.
Later, on line 28, the compiler saw the definition of the convolve function, this time returning Matrix, which is incompatible with the previous (implicit) declaration.
The solution, in your case, is to define the function before it is used. In C, and more generally in most programming languages, you need to define (or at least declare) things before they are used. The main function should always be the last one in your source file since it uses other functions but no other function uses it¹.
If the function was defined in a different source file, you would need to declare it in a header file (.h), and include the header file in the .c files where the function is used.
Any halfway decent compiler would at least explicitly warn about implicit declarations: they're permitted, but they're a bad idea. Visual Studio can do it, but I think you need to raise the warning level from the default.
¹ Except in highly unusual programs that call main recursively.

Is there a way in C to have the compiler/linker give an error if a function is not defined?

In my case I am writing a simple plugin system in C using dlfcn.h (linux). The plugins are compiled separately from the main program and result in a bunch of .so files.
There are certain functions that must be defined in the plugin in order for the the plugin to be called properly by the main program. Ideally I would like each plugin to have included in it a .h file or something that somehow states what functions a valid plugin must have, if these functions are not defined in the plugin I would like the plugin to fail compilation.
I don't think you can enforce that a function be defined at compile time. However, if you use gcc toolchain, you can use the --undefined flag when linking to enforce that a symbol be defined.
ld --undefined foo
will treat foo as though it is an undefined symbol that must be defined for the linker to succeed.
You cannot do that.
It's common practice, to only define two exported functions in a library opened by dlopen(), one to import functions in your plugin and one to export functions of your plugin.
A few lines of code are better than any explanation:
struct plugin_import {
void (*draw)(float);
void (*update)(float);
};
struct plugin_export {
int (*get_version)(void);
void (*set_version)(int);
};
extern void import(struct plugin_import *);
extern void export(struct plugin_export *);
int setup(void)
{
struct plugin_export out = {0};
struct plugin_import in;
/* give the plugin our function pointers */
in.draw = &draw, in.update = &update;
import(&in);
/* get our functions out of the plugin */
export(&out);
/* verify that all functions are defined */
if (out.get_version == NULL || out.set_version == NULL)
return 1;
return 0;
}
This is very similar to the system Quake 2 used. You can look at the source here.
With the only difference, Quake 2 only exported a single function, which im- and exports the functions defined by the dynamic library at once.
Well after doing some research and asking a few people that I know of on IRC I have found the following solution:
Since I am using gcc I am able to use a linker script.
linker.script:
ASSERT(DEFINED(funcA), "must define funcA" ) ;
ASSERT(DEFINED(funcB), "must define funcB" ) ;
If either of those functions are not defined, then a custom error message will be output when the program tries to link.
(more info on linker script syntax can be found here: http://www.math.utah.edu/docs/info/ld_3.html)
When compiling simply add the linker script file after the source file:
gcc -o test main.c linker.script
Another possibility:
Something that I didn't think of (seems a bit obvious now) that was brought to my attention is you can create small program that loads your plugin and checks to see that you have valid function pointers to all of the functions that you want your plugin to have. Then incorporate this into your build system, be it a makefile or a script or whatever. This has the benefit that you are no longer limited to using a particular compiler to make this work. As well as you can do some more sophisticated checks for other other things. The only downside being you have a little more work to do to get it set up.

Passing pointers to structures into C functions from TCL using SWIG

I'm attempting to build a test framework in TCL that will allow me to perform scripted tests on a remote device over a TCP socket. There already exists a Visual Basic interface and with SWIG in Ubuntu I'm reusing the C functions that it calls to build a shared library that will work as an extension to TCL. I have had success at incorporating basic functions, such as opening/closing sockets, and basic read/writes to single memory addresses on the device using SWIG's typemaps.i to provide pointers (*OUTPUT) to the readAddress function to return address values to TCL.
The problem is that for this to be useful I am going to have to incorporate a large number of Remote Procedure Calls which pass complicated data types into (and back out of!) the device. As a proof of concept I'm attempting to get a relatively simple function working. This attempts to read default test parameters via an RPC; a pointer to a struct is provided for the function to use for the results: rpc_testDefaults ( testDefaults_t *testDefaults ).
The typedef for testDefaults_t is in testDefaults.h, which is in the style of the following:
// testDefaults.h
#include <stdint.h>
typedef uint32_t customType_t;
typedef struct
{
customType_t varName1; // Description
uint32_t varName2; // Description
// 13 more uint32_t elements
} testDefaults_t;
// Two more struct type definitions
testDefaults.c is along the lines of this:
// testDefaults.c
#include "testDefaults.h"
// #ifdefs to compile as 'client' OR 'server' (defaults to 'client')
rpc_testDefaults ( testDefaults_t, *testDefaults )
{
// function
}
My SWIG interface file looks like this:
// rpcTest.i
%module rpcTest
%include <cpointer.i>
%include "testDefaults.h"
%pointer_functions(testDefaults_t, testDefaults);
//%apply int *OUTPUT {testDefaults_t, *testDefaults};
%{
#include "testDefaults.h"
extern int rpc_testDefaults ( testDefaults_t, *testDefaults )
}%
extern int rpc_testDefaults ( testDefaults_t, *testDefaults )
There are many other .c and header files in the same folder which support this function and the others which I mentioned I got working.
I run swig -tcl -debug-typedef rpcTest.i which gives me rpcTest_wrap.c, I can see that the testDefaults_t has been recognised as a type/scope as is has a section in the debug output (it's also included in the unnamed scope section: testDefaults_t -> testDefaults_t).
I run gcc -fPIC -DCLIENT_FLAG -c *.c -I/usr/include/tcl8.5 and I get an error from a line in the SWIG output file: rpcTest_wrap.c:1803:3: error: unknown type name 'testDefaults_t' (plus a lot more errors derived from this). The line in question is the first line in this function:
static testDefaults_t *new_testDefaults() {
return (testDefaults_t *)malloc(sizeof(testDefaults_t));
}
Which I believe is cpointers.i creating a function for TCL to 'create' a pointer to that struct.
I have a feeling this is something to do with gcc including files in the wrong order, but I'm at a loss as to what to do next. I've tried many combinations of defining the header in various places in the interface file and this is the combination that gives the least errors :). You can see my commented-out partial attempt at using typemaps instead of cpointers but I'm even more clueless with these, I managed it for a pointer to a single value but it didn't seem to be working for a struct with it's own type. It did compile without error though.
So is it possible to get what I'm trying to achieve working using cpointers.i? Any suggestions on how to overcome the compiler issue? Would I be better off learning how to use typemaps? Let me know where I can provide more detail if it would help, I may be leaving out crucial information as I've had to summarize and change all the names as this is company stuff.
Any help/criticism would be greatly appreciated!
Looking into the rpcTest_wrap.c file I noticed that the include for testDefaults.h was right after the group of functions that were attempting to use it. I replaced "int" in the interface file with testDefaults_t (I think this is correct), ran SWIG, edited the output (dangerous I know!) so that the include happened just before these functions, and it compiles fine. I can load the shared library into TCL and run the new functions.
However, and this is perhaps a new question, [in TCL] using the new functions to create a pointer, feed it into rpc_testDefaults, and attempting to dereference the resulting pointer using testDefaults_value just returns another pointer. I realize that I can't just dereference a struct, but I have no idea how to dereference individual elements. Any tutorials I can find only refer to dereferencing non-structs (and none of these tutorials are for TCL). Something somewhere mentioned that there are similarities between structs and TK widgets so I'll have a look into this, but I'm still not sure is what I'm attempting to do even possible, and if it is is this the right way to do it.
Again, what I am attempting to do is in TCL, access individual elements of a struct which has been returned from (or fed into) a C function via a pointer.
UPDATE: I got this working in the end by using the functions SWIG generates which I discovered in the end of the wrapper file. cpointer.i wasn't needed at all. In TCL I first create a pointer using the new function new_testDefaults which returns a string with in the form of a TCL style pointer. I pass this pointer into rpc_testDefaults, which returns nothing as it was actually a void function. I can then access individual elements from the struct referenced by the above pointer by setting it as an argument to the elementName_get and elementName_set functions generated by SWIG. The next task is to get more complicated functions working, structs in structs etc, but now that I'm familiar with the methodology it shouldn't be too hard.

Importance of main() parameters

I'm starting out on SDL using CodeBlocks IDE. I got an error undefined reference to 'SDL_main'. I researched and found out that you need to have the parameters
int argc, char* args[]
in the main(). I added those and the code compiled and worked. My question is, how important are the parameters for the linker to be able to work?
Main parameters have to be there because SDL defines main internally as ......SDL_main(int argc, char *argv[])... depending on the system and does some initialization.
Just include main parameters, it doesn't matter if you're not using them.

How to write a quine program without main()

I went through all sorts of quine problems, but my task was to get a quine problem without main(), and loops are also forbidden.
Without loop, it is easy, but I can't figure out how to write one without main(). Can anyone help me or provide me with a link?
You cannot create a (non-freestanding) C program without a main() function. Thus, creating a quine in C without a main() is impossible in the usual sense.
That said, depending on how you define a quine, you might be able to construct a source file which fails to compile, but for which the compile error (on a certain specific compiler) is the contents of the source file.
First thing its impossible to write program without main function because compiler always starts execution from main() function, without main function linker will not be aware of start of data segment.
Yeah but playing with some tricks with preprocessor you can do it, but this is not a good method to do that.
http://www.gohacking.com/2008/03/c-program-without-main-function.html
This might help you.
Take a look here too:
Is a main() required for a C program?
#include <stdio.h>
int
foo(void) {
printf("pong!\n");
return 0;
}
int main() __attribute__((weak, alias("foo")));
There is main() declaration, but not definition.

Resources