Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

Beef posted:

Your business case is that the cost of upgrading to a compute environment from this decade is less than the cost of a certain programming going on a rampage and literally sacrificing security guideline managers on an altar to productivity.

has this environment been audited by a trusted party for work in this sector? let me generate 200 hours of meetings to discuss. by the way, this won't impact the ship date, right?
:suicide::suicide::suicide::suicide::suicide:

moving literally anything into a secure environment takes months of effort. i am incredibly glad i don't deal with that.

Adbot
ADBOT LOVES YOU

Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!
I have a make question, this seems like the best thread for it. We're using ar to create static libraries with a rule roughly like this:
code:
$(TARGET): $(GCH) $(OBJECTS) $(EXTERNAL_LIBS) | $(TARGETDIR) $(OBJDIRS)
    @echo Archiving library
    $(SILENT) ar -rcs $(TARGET) $(OBJECTS)
This has issues with incremental builds when someone changes a filename, ar will happily leave the object file in the library under the old name and then we get "multiple defined symbol" errors when linking an exe with the library. As far as I can tell, there's no ar flags to make it create the archive from scratch even if it already exists. I was hoping there'd be some way to create a rule that runs if the library is older than the makefile (indicating the file manifest has changed) which deletes the library, and obviously have that rule run before the rule above. Thought about from every which way and I can't think how to do this. Seems like ar is totally spitting on the whole premise of make by forcing the existing library file from a previous build to be an input to its own rule.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
Normally you just unconditionally delete the .a first because updating the existing archive rather than creating it from scratch is not a meaningful optimization.

Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!

Plorkyeran posted:

Normally you just unconditionally delete the .a first because updating the existing archive rather than creating it from scratch is not a meaningful optimization.

Fair enough, I can just add a delete to the recipe. Bizarre to me that it can't be accomplished with a flag to ar but it is what it is. Thanks!

baby puzzle
Jun 3, 2011

I'll Sequence your Storm.
Is there a less verbose way to do this kind of extremely simple formatting? Does it need to take 3 lines and a variable to format some text???

code:
	std::stringstream scoreText;
	scoreText << "Score: " << std::setprecision( 2 ) << std::fixed << game.GetScorePercentage() << "%";
	m_Score.SetText( scoreText.str().c_str() );

Xarn
Jun 26, 2015

baby puzzle posted:

Is there a less verbose way to do this kind of extremely simple formatting? Does it need to take 3 lines and a variable to format some text???

code:
	std::stringstream scoreText;
	scoreText << "Score: " << std::setprecision( 2 ) << std::fixed << game.GetScorePercentage() << "%";
	m_Score.SetText( scoreText.str().c_str() );

Either fmtlib or sprintf if you have to. Just be careful with sprintf, because it sneers at boring things like type safety :v:

Doc Block
Apr 15, 2003
Fun Shoe
Just use printf().

Don't use sprintf(), it's unsafe. If you need to format a C string, use snprintf() instead, since it won't cause buffer overruns.

still no type safety though :rock:

Doc Block fucked around with this message at 19:48 on Dec 16, 2016

Spatial
Nov 15, 2007

There's probably some library that does printf with variadic templates to make it magical and neat.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
One was even linked above.

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today
Clang will warn you if you're using a static format string that disagrees with the types of your arguments. Not as nice as a template solution, but enough to be comfortable using the printf family when it's called for.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
I'm looking into profiling a real-time application, but am not sure where to start. Once I've compiled my app with the -pg flag and debug symbols, how would I go about actually accessing the recorded timing data from within the app itself?

E: The idea is that I'll ultimately be able to quickly test the performance impact of lots of different actions at the very least in real-time without closing the app and preferably from within the app itself.

E2: Alternatively, how would I go about running an app like oprofile from within my app, then read the output back to the parent? I feel like something like that would set off a shittonne of security problems especially in Windows.

Joda fucked around with this message at 23:50 on Dec 19, 2016

netcat
Apr 29, 2008
I built some code that had a multiple defintions linker error that appeared on one machine but not another, with the same version of gcc (4.8.3 I believe). How can that happen? The code looked something like

code:
// foo.h
int foo(x, y, z);

// foo.c
int foo(x, y, z) { /* stuff */ }

// bar.h
int foo(x, y);

// bar.c
int foo(x, y) { /* some other stuff */ }
Seems like that should always fail? Can the linker order matter somehow?

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Why would that be a problem? I may be wrong, but iirc if their signatures are different, they're treated as different functions by gcc/ld.

eth0.n
Jun 1, 2012

Joda posted:

Why would that be a problem? I may be wrong, but iirc if their signatures are different, they're treated as different functions by gcc/ld.

Presumably, this is C, which doesn't have overloading. Not sure why it would be accepted inconsistently, though. Maybe it's getting compiled as C++ on one machine?

netcat
Apr 29, 2008

eth0.n posted:

Presumably, this is C, which doesn't have overloading. Not sure why it would be accepted inconsistently, though. Maybe it's getting compiled as C++ on one machine?

Yeah it's C. It's the same cmake/make files in both places also, so getting compiled as c++ in one place doesn't really seem likely but ?? ? who knows

Xarn
Jun 26, 2015

netcat posted:

Yeah it's C. It's the same cmake/make files in both places also, so getting compiled as c++ in one place doesn't really seem likely but ?? ? who knows

dump symbols, if they are eye-stabbingly horrible, its compiled as C++ :v:

That Turkey Story
Mar 30, 2003

I was a guest on CppCast this week talking about Regular Void and a few of my other standards proposals, for anyone who wants to hear my nasally nerd voice:

Ika
Dec 30, 2004
Pure insanity

Is there an existing implementation of a list that does the following? I just wrote my own implementation for fun, but now I'm thinking an existing library may have better performance and this was a bit crazy.

- thread-safe bidirectional iterators for multithreaded access
- iterator::Next() / ::Prev() continue to work even after the iterator was removed from the list. (And even if the original next/prev values were also removed.) This way one thread can delete elements while another thread is iterating over it and the iteration will not break. The contents are reference counted so they don't get erased until any iterator references also are gone.

The first point is easy using a spinlock, but the second point ended up getting a bit more complicated than expected.

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Is there a simple C++ library (under MIT/similar) that just opens various popular image formats (png, bmp, tiff, jpg) and gives you a pointer to a simple array of color channel bytes? I've been looking around and there are a lot of image libraries but every single one of them seem to be geared towards image manipulation rather than simply opening and decoding (also, lots of them are under GPL.) There's SOIL, which is great if I just wanted to load a texture, but it doesn't offer a way to access the raw bit stream in local memory.

I'm half considering just using libpng and having all my images as pngs, but I would like the option to load images in other formats without having to implement loaders for everything.

csammis
Aug 26, 2003

Mental Institution
OpenCV is BSD licensed and ridiculous overkill for your needs but it'll do the job with very little code. Load the image using cv::imread, that returns a cv::Mat from which you can get the channels (in BGR order!) using cv::split.

icantfindaname
Jul 1, 2008


I'm trying to write a program in C that parses a string containing 5 currencies and converts them to dollars, character by character with getchar(), so for example the input "$500£500¥500€500₹500"

What I have works correctly except for a bizarre bug where the value after the amount in pounds always shows up zero, so the above input gives this output

code:
$500
$823 in sterling
$0 in yen
$683 in euros
$8 in rupees
The input $500£500$500 gives

code:
$500
$823 in sterling
$0
My code is this. I use a C string to hold the characters grabbed from stdin before converting them to an integer, and if you print the raw string containing the characters supposed to be $500 in the above it's super hosed up, the characters themselves seem to be random numbers. What the heck is the problem?

code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * append(char *str, char c)
{
        size_t len = strlen(str);
	char *str2 = malloc(len + 1 + 1);
	strcpy(str2, str);
        str2[len] = c;
        str2[len+1] = '\0';
	free(str);
	return str2;
}

int main ()
{
	int n, total = 0;
	char *str = malloc(sizeof(char));

	printf("Please enter a sum of money in sterling, yen, rupees or euros: ");

	for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {

		if (c == 0x24) {
			while ((c = getchar()) != '\n' && c != EOF) {
				if (c == 0xC2 || c == 0xE2) { ungetc(c, stdin); break; }

				str = append(str, c);
			}

			n = atoi(str);

			printf("%d %d %d\n", str[0], str[1], str[2]);

			printf("$%d\n", n);

			total += n;

			free(str);

			str = malloc(sizeof(char));

			continue;

		}

		if (c == 0xC2) {
			c = getchar();
			if (c == 0xA3) {
				while ((c = getchar()) != '\n' && c != EOF) {
					if (c == 0x24 || c == 0xE2 || c == 0xC2) { ungetc(c, stdin); break; }

					str = append(str, c);
				}

				n = atoi(str);

				n = n * 1000 / 607;

				printf("$%d in sterling\n", n);

				total += n;

        	                free(str);

     	           	        str = malloc(sizeof(char));

				continue;
			}

                        if (c == 0xA5) {
                                while ((c = getchar()) != '\n' && c != EOF) {
                                        if (c == 0x24 || c == 0xE2 || c == 0xC2) { ungetc(c, stdin); break; }

                                        str = append(str, c);
                                }

                                n = atoi(str);

                                n = n * 100 / 10404;

                                printf("$%d in yen\n", n);

                                total += n;

				str = malloc(sizeof(char));

				continue;
                        }

		}

		if (c == 0xE2) {
                        c = getchar();
			c = getchar();
                        if (c == 0xAC) {
                                while ((c = getchar()) != '\n' && c != EOF) {
                                        if (c == 0x24 || c == 0xC2 || c == 0xE2) { ungetc(c, stdin); break; }

                                        str = append(str, c);
                                }

                                n = atoi(str);

                                n = n * 1000 / 732;

                                printf("$%d in euros\n", n);

                                total += n;

				str = malloc(sizeof(char));

				continue;
                        }

                        if (c == 0xB9) {
                                while ((c = getchar()) != '\n' && c != EOF) {
                                        if (c == 0x24 || c == 0xC2 || c == 0xE2) { ungetc(c, stdin); break; }

                                        str = append(str, c);
                                }

                                n = atoi(str);

                                n = n * 1000 / 61903;

                                printf("$%d in rupees\n", n);

                                total += n;

				str = malloc(sizeof(char));

				continue;
                        }

		}
	} 

	

	free(str);

	return 0;

}

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Don't you need to use wide characters to read your input for £/¥/€/₹ since they don't exist in ASCII?

icantfindaname
Jul 1, 2008


Joda posted:

Don't you need to use wide characters to read your input for £/¥/€/₹ since they don't exist in ASCII?

Yeah, those characters exist as multiple characters in stdin, you can use multiple getchar() calls to pull them out. ₹ is 0xE2, 0x82, 0xB9

That's not the problem though, it works fine except after a pounds-denominated value

fritz
Jul 26, 2003

csammis posted:

OpenCV is BSD licensed and ridiculous overkill for your needs but it'll do the job with very little code. Load the image using cv::imread, that returns a cv::Mat from which you can get the channels (in BGR order!) using cv::split.

It also just wraps libpng/libjpeg/libtiff.

csammis
Aug 26, 2003

Mental Institution
Sure but is that a problem? I didn't get the impression that Joda is necessarily looking for bespoke image decoding libraries, just that they were looking to avoid writing wrappers around libjpeg/libpng/etc themselves

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe
Oh :doh: . I decided to take a look at the source code for SOIL to see if I could modify it to give me access to a CPU-side pointer rather than an OpenGL texture reference, and it turns out they use something called stb_image which looks like exactly what I'm looking for. Single-header, loads and saves all the usual subjects, not a lot of bloat. Wonder why it doesn't show up when you google for open image libraries/similar.

E: Also, yeah I was just looking for a wrapper so I could avoid writing it myself. If I was willing to accept a lot of bloat, there were a couple of options, but I really wanted to avoid including a massive image manipulation library just to load some textures/images.

Joda fucked around with this message at 04:59 on Dec 29, 2016

Xerophyte
Mar 17, 2008

This space intentionally left blank

Joda posted:

Is there a simple C++ library (under MIT/similar) that just opens various popular image formats (png, bmp, tiff, jpg) and gives you a pointer to a simple array of color channel bytes? I've been looking around and there are a lot of image libraries but every single one of them seem to be geared towards image manipulation rather than simply opening and decoding (also, lots of them are under GPL.) There's SOIL, which is great if I just wanted to load a texture, but it doesn't offer a way to access the raw bit stream in local memory.

I'm half considering just using libpng and having all my images as pngs, but I would like the option to load images in other formats without having to implement loaders for everything.
For slightly more format support:

OpenImageIO is the industry standard for image IO nowadays. Especially in VFX -- they support all manner of deep EXR malarky -- but it's useful in general and good to be familiar with. BSD licensed. To get raw pixel data you'd do something like
code:
oiio::ImageBuf image("path/to/image.png");
image.read(0, 0, true, oiio::TypeDesc::UINT8);
uint8_t* pixels = static_cast<uint8_t*>(image.localpixels());
// do stuff with pixels
FreeImage (C) and FreeImagePlus (C++ wrapper, some features missing) have very good format support and are fairly lightweight, although the C API at least is more cumbersome. Their HDR support is a bit lacking: I spent some time trying to convince the maintainer that operations on HDR formats shouldn't clamp the data to [0, 1] since that kinda misses the point and I don't think he quite got it. It's available under a few different licences, one of them being GPL but also a custom and more permissive "FreeImage Public License" -- we're using it commercially at Autodesk, so I believe it's been decently lawyered. To get raw pixel data you'd do something like
code:
FREE_IMAGE_FORMAT fif = FreeImage_GetFileType("path/to/image.png", 0);
FIBITMAP* bitmap = FreeImage_Load(fif, "path/to/image.png");
uint8_t* pixels = static_cast<uint8_t*>(FreeImage_GetBits(bitmap));
// do stuff with pixels
FreeImage_Unload(bitmap);
Code samples are not strictly representative of real-world use (or, y'know, tested). Neither library will give you data as packed RGB(A) arrays by default in all cases or anything nice like that. OIIO has a pretty flexible system for changing the strides and buffer orders; FreeImage, not so much

Xerophyte fucked around with this message at 07:39 on Dec 29, 2016

Dylan16807
May 12, 2010

icantfindaname posted:

I'm trying to write a program in C that parses a string containing 5 currencies and converts them to dollars, character by character with getchar(), so for example the input "$500£500¥500€500₹500"

What I have works correctly except for a bizarre bug where the value after the amount in pounds always shows up zero, so the above input gives this output
You're not initializing str when you malloc it. That could cause all sorts of weirdness.

icantfindaname
Jul 1, 2008


Dylan16807 posted:

You're not initializing str when you malloc it. That could cause all sorts of weirdness.

If I set the value of the pointer with strcpy(str, " "); it still gives the error

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

icantfindaname posted:

What the heck is the problem?
code:
				if (c == 0xC2 || c == 0xE2) { ungetc(c, stdin); break; }
					if (c == 0x24 || c == 0xE2 || c == 0xC2) { ungetc(c, stdin); break; }
                                        if (c == 0x24 || c == 0xE2 || c == 0xC2) { ungetc(c, stdin); break; }
                                        if (c == 0x24 || c == 0xC2 || c == 0xE2) { ungetc(c, stdin); break; }
                                        if (c == 0x24 || c == 0xC2 || c == 0xE2) { ungetc(c, stdin); break; }
One of these things is not like the others.
Also that test should probably be a function so that you don't cause a problem like this.
Also, when the character is an ascii character, your code might be more readable like
code:
if (c == '$')
, and when it's not, constants could make it more readable, eg.
code:
static const char kYen[] = {0xE2, 0xWhatever, 0xWhatever};
...
if (c == kYen[0])

roomforthetuna fucked around with this message at 03:48 on Dec 30, 2016

icantfindaname
Jul 1, 2008


Okay, the problem was in the dynamic allocation of memory for the holder string. Man, memory management is a nightmare

Star War Sex Parrot
Oct 2, 2003

C/C++ Programming Questions: Man, memory management is a nightmare

tractor fanatic
Sep 9, 2005

Pillbug
Can I use CRTP to make mixin constructors? I don't think it's possible without UB but maybe there's hope:

C++ code:
template <class Der>
class stringable{
public: stringable(const std::string & s) { static_cast<this>(Der*)->intval = std::stoi(s); }
};

class D : public stringable<D>{
public:
	int intval;
	using stringable<D>::stringable;
};
Basically, I have this weird dream to turn C++ into Ada, or my idea of what Ada is, and in my program I have a ton of different integer types which express different kinds of indices and values etc. I want to use static type checking to prevent improper mixing of these integer types, so I have a bunch of mixins for simple integer ideas like additivity:

C++ code:
template <class D, class DiffType = D> class addable{
public:
	D & operator += (const DiffType & o)
		{ expose_base(*static_cast<D*>(this)) += expose_base(o); return static_cast<D&>(*this); }
	D operator + (const DiffType & o) const
		{ return D{ expose_base(*static_cast<const D*>(this)) + expose_base(o) }; }
		
	D & operator -= (const DiffType & o)
		{ expose_base(*static_cast<D*>(this)->p) -= expose_base(o); return static_cast<D&>(*this); }
	D operator - (const DiffType & o) const
		{ return D{ expose_base(*static_cast<const D*>(this)) - expose_base(o) }; }
}

class time_duration : public addable<time_duration>{
	int t;
public:
	friend int& expose_base(time_duration & o) { return o.t; }
};

class time : public addable<time, time_duration>{
	int t;
public:
	friend int& expose_base(time & o) { return o.t; }
};
Sort of like units, but it also distinguishes between absolute values and differences, etc.

tractor fanatic fucked around with this message at 19:08 on Jan 7, 2017

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today
Where's the UB in your example?

Aesthetically speaking, it might be a bit prettier if you used "explicit operator T&()" rather than "expose_base".

eth0.n
Jun 1, 2012

Ralith posted:

Where's the UB in your example?

Is it OK to access a derived class's data from a base constructor? I thought until after the base constructor was finished, the object wasn't actually of the derived class's type. Is it defined what would happen if the derived class constructor also initialized "intval"?

Ralith
Jan 12, 2011

I see a ship in the harbor
I can and shall obey
But if it wasn't for your misfortune
I'd be a heavenly person today

eth0.n posted:

Is it OK to access a derived class's data from a base constructor? I thought until after the base constructor was finished, the object wasn't actually of the derived class's type. Is it defined what would happen if the derived class constructor also initialized "intval"?
Oh, that does look a bit sketchy, though I'd have to check the standard to be sure. I was focusing on the second code block. "D(const std::string &s) : intval{std::stoi(s)} {}" is a lot shorter than all that boilerplate anyway, so at least that particular example is a bit difficult to rationalize. Relatedly: please mark single-argument constructors as explicit.

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...

tractor fanatic posted:

Can I use CRTP to make mixin constructors? I don't think it's possible without UB but maybe there's hope:

C++ code:

template <class Der>
class stringable{
public: stringable(const std::string & s) { static_cast<this>(Der*)->intval = std::stoi(s); }
};

class D : public stringable<D>{
public:
	int intval;
	using stringable<D>::stringable;
};

For construction, it would be simpler (and completely legal) to do this, I think:
code:

class I { int intval; public: I(int i) : intval(i) {} };  // sorry about the layout, typing on tablet

template <typename D> class stringable : public D
{
public:
  stringable(string s) : D(std::stoi(s)) {}
};

stringable<I> foo("42");

raminasi
Jan 25, 2005

a last drink with no ice
Anyone have any idea why Visual Studio 2015 might seem to be ignoring my -Zm flag? I get the "use a higher -Zm value" error message even when I'm using the value it tells me to.

Woebin
Feb 6, 2006

Is anyone sitting on some good online resources for idiots grappling with C++? The OP was last updated just over six years ago and a bunch of the links are dead. I'm on my second attempt at this university course and have my final exam tomorrow, regardless of whether I make it or not I could really use something that'll help me understand stuff in the future. Stuff like keeping track of pointers, references and copies throws me off constantly, as well as deciding what goes in the header and what goes in cpp and so on. Basically C++ makes me feel really dumb. My first language was Java, for what it's worth.

Not asking anyone to sit down and explain stuff to me, and not asking for anything that I can skim and somehow ace things tomorrow, just hoping that I can at some point understand this drat language better. So yeah. If someone's sitting on a great link or something, I'd love that.

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
C is really defined at a lower level of abstraction than Java. You can try to program in C++ like you would in Java, without worrying too much about how things work under the covers, and that's usually the right idea; but C++ exposes that lower level of abstraction in a lot of different ways, and it's that difference in abstraction levels that drives a lot of the rules and pitfalls of programming in C++, and you really do need to internalize that lower level of abstraction and at least the basics of how various ideas from C++ map down onto it before things will really "click" for you. That's why people often suggest learning C before learning C++; C is really just an inferior language in many ways, so for actually doing low-level programming it's not really a good idea, but for learning low-level programming it's much more direct, and then you can incrementally add in various C++ concepts and think about how they're implemented as you go.

It's hard to make recommendations given that you have an exam tomorrow, because really I want to suggest that you first read some C material on pointers, headers, etc., but with that little time I'm afraid you'll just end up confused. Probably you should just have learned by this point in your university experience not to try to cram everything the night before the test.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply